1

I have a query which finds duplicate IDs

 SELECT uniqueID2, count(uniqueID2) as 'count'
                                  FROM gpDetailAfterMultiplier
                                   group by uniqueID2
                                  having count(uniqueID2) > 1

this produces an output something like:

uniqueID2     count
111111111       2
111111112       2
111111113       2
111111114       2

How do I automatically delete one of the two duplicates?

I can do this one at a time by doing

DELETE top(1) from gpDetailAfterMultiplier where UniqueID2 = '111111111'

is there any way to do this so that it automatially 'loops' through each result and deletes one of the two duplicates for each unique id?

neeko
  • 1,812
  • 8
  • 44
  • 65

1 Answers1

1

Try this:

WITH CTE AS(
   SELECT *,
       RN = ROW_NUMBER()OVER(PARTITION BY uniqueID2 ORDER BY uniqueID2)
   FROM gpDetailAfterMultiplier
)
DELETE FROM CTE WHERE RN > 1

It will delete all duplicates from the table.

See result in Fiddle (Used SELECT query in fiddle to see which records are going to be deleted).

juergen d
  • 195,137
  • 36
  • 275
  • 343
Raging Bull
  • 18,113
  • 13
  • 47
  • 53