Finding duplicate values in a SQL table

后端 未结 30 4005
南旧
南旧 2020-11-21 13:18

It\'s easy to find duplicates with one field:

SELECT name, COUNT(email) 
FROM users
GROUP BY email
HAVING COUNT(email) > 1

So if we have

30条回答
  •  既然无缘
    2020-11-21 14:03

    If you want to find duplicate data (by one or several criterias) and select the actual rows.

    with MYCTE as (
        SELECT DuplicateKey1
            ,DuplicateKey2 --optional
            ,count(*) X
        FROM MyTable
        group by DuplicateKey1, DuplicateKey2
        having count(*) > 1
    ) 
    SELECT E.*
    FROM MyTable E
    JOIN MYCTE cte
    ON E.DuplicateKey1=cte.DuplicateKey1
        AND E.DuplicateKey2=cte.DuplicateKey2
    ORDER BY E.DuplicateKey1, E.DuplicateKey2, CreatedAt
    

    http://developer.azurewebsites.net/2014/09/better-sql-group-by-find-duplicate-data/

提交回复
热议问题