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,930
  • 8
  • 44
  • 67

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
  • 201,996
  • 37
  • 293
  • 362
Raging Bull
  • 18,593
  • 13
  • 50
  • 55