Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 find multiple entries

Author  Topic 

purplecruz
Starting Member

7 Posts

Posted - 2008-12-31 : 12:53:06
I have been trying to find some duplicate entries in a table but the simple count(*) > 1 method is not enough in this case.

I have a table with plots (plot_ID) that are located in stands (stand_ID). I would like to find if one plot is in more than one stand. The problem is that any plot may have multiple trees in it, so there could be more than one of the same plot_IDs per stand but it should only be associated with one stand_ID.

Any help would be greatly appreciated.
I can also provide an example to clarify if needed.

Thanks!

Stacy

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2008-12-31 : 12:53:53
You need to show us some sample data.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

purplecruz
Starting Member

7 Posts

Posted - 2008-12-31 : 13:04:14
Here is an example:

stand_ID Plot_ID
12345 1
12345 1
12345 1
12345 2
12345 2
45678 3
45678 3
67890 2
67890 2
67890 4

In this case there are two plots (1 and 2) in the first stand (12345). Plot 1 has 3 trees and plot 2 has two trees.
The next stand(45678) only has one plot(plot 3) with two trees.
In the last plot (67890) there are two plots (2 and 4), but plot 2 has already been used in stand 12345. That is the error I would like to find.
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2008-12-31 : 13:26:58
Try this:

SELECT Plot_ID, COUNT(*) AS DupeCount
FROM (SELECT DISTINCT stand_ID, Plot_ID FROM YourTable) t
GROUP BY Plot_ID
HAVING COUNT(*) > 1

Untested...


Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

purplecruz
Starting Member

7 Posts

Posted - 2008-12-31 : 13:52:19
Thank You-that worked!
Just curious-why is the t needed before the Group By?
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2008-12-31 : 15:19:16
An alias is needed for a derived table. You can call it anything, I just used t.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -