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
 Need help with duplicate query

Author  Topic 

pjyelton
Starting Member

4 Posts

Posted - 2010-03-19 : 19:38:53
Hello, I need help with writing a query. Basically what I want to do is give a unique identifier for each group of duplicates in a table. For example, if this is my data:


FIRST LAST AGE DUPENUM
BOB JONES 16
BOB JONES 16
BOB JONES 34
TOM ADAMS 21
JOE BROWN 37
TOM ADAMS 21
JOE BROWN 37

and I want my duplicate to be FIRST/LAST/AGE, after the query is run the table looks like this:

FIRST LAST AGE DUPENUM
BOB JONES 16 1
BOB JONES 16 1
BOB JONES 34
TOM ADAMS 21 2
JOE BROWN 37 3
TOM ADAMS 21 2
JOE BROWN 37 3

So each new duplicate group gets the next available dupenum.

Thanks for any help!

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2010-03-19 : 20:10:32
what is the version of SQL Server you are using ?


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

pjyelton
Starting Member

4 Posts

Posted - 2010-03-19 : 23:47:02
2005, although in the end this code will instead be run as a stored procedure through Java.
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2010-03-20 : 00:04:07
[code]
DECLARE @sample TABLE
(
[FIRST] varchar(10),
[LAST] varchar(10),
[AGE] int
)
INSERT INTO @sample
SELECT 'BOB', 'JONES', 16 UNION ALL
SELECT 'BOB', 'JONES', 16 UNION ALL
SELECT 'BOB', 'JONES', 34 UNION ALL
SELECT 'TOM', 'ADAMS', 21 UNION ALL
SELECT 'JOE', 'BROWN', 37 UNION ALL
SELECT 'TOM', 'ADAMS', 21 UNION ALL
SELECT 'JOE', 'BROWN', 37

SELECT s.[FIRST], s.[LAST], s.AGE, d.[DUPENUM]
FROM @sample s
LEFT JOIN
(
SELECT [FIRST], [LAST], AGE,
[DUPENUM] = dense_rank() OVER (ORDER BY [FIRST], [LAST], AGE)
FROM @sample
GROUP BY [FIRST], [LAST], AGE
HAVING COUNT(*) > 1
) d ON s.[FIRST] = d.[FIRST]
AND s.[LAST] = d.[LAST]
AND s.[AGE] = d.[AGE]

/*
FIRST LAST AGE DUPENUM
---------- ---------- ----------- --------------------
BOB JONES 16 1
BOB JONES 16 1
BOB JONES 34 NULL
TOM ADAMS 21 3
JOE BROWN 37 2
TOM ADAMS 21 3
JOE BROWN 37 2

(7 row(s) affected)
*/

[/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

pjyelton
Starting Member

4 Posts

Posted - 2010-03-20 : 00:17:21
Brilliant, thanks!!!
Go to Top of Page
   

- Advertisement -