Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find duplicates for several columns exclusive ID-column

i've found a lot of answers on how to find duplicates including the PK-column or without focus on it as this:

If you have a table called T1, and the columns are c1, c2 and c3 then this query would show you the duplicate values.

SELECT C1, C2, C3, count(*)as DupCount
 from T1
 GROUP BY C1, C2, C3
 HAVING COUNT(*) > 1

But a more common requirement would be to get the ID of the all duplicates that have equal c1,c2,c3 values.

So i need following what doesn't work because the id must be aggregated:

SELECT ID
 from T1
 GROUP BY C1, C2, C3
 HAVING COUNT(*) <> 1

(The ID of all duplicates must be different but the columns must be equal)

Edit:

Thank you all. I'm always suprised how fast people give excellent answers on Stackoverflow!

like image 543
Tim Schmelter Avatar asked Dec 10 '22 10:12

Tim Schmelter


1 Answers

There is a lot of versions suggested here but I think I came up with a new one.

select *
from @T as T1
where exists (select *
              from @T as T2
              where
                T1.ID <> T2.ID and
                T1.C1 = T2.C1 and
                T1.C2 = T2.C2 and
                T1.C3 = T2.C3)
like image 84
Mikael Eriksson Avatar answered Jan 14 '23 00:01

Mikael Eriksson