Finding duplicate values in a SQL table

后端 未结 30 4006
南旧
南旧 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 13:52

    This is the easy thing I've come up with. It uses a common table expression (CTE) and a partition window (I think these features are in SQL 2008 and later).

    This example finds all students with duplicate name and dob. The fields you want to check for duplication go in the OVER clause. You can include any other fields you want in the projection.

    with cte (StudentId, Fname, LName, DOB, RowCnt)
    as (
    SELECT StudentId, FirstName, LastName, DateOfBirth as DOB, SUM(1) OVER (Partition By FirstName, LastName, DateOfBirth) as RowCnt
    FROM tblStudent
    )
    SELECT * from CTE where RowCnt > 1
    ORDER BY DOB, LName
    

提交回复
热议问题