如何列出重复记录?

时间:2014-11-03 04:11:41

标签: sql-server sql-server-2008

我有以下表结构:

id|date|studenttypeid|name|audituser
1|.....|4|Jason|....
2|.....|4|Robin|....
3|.....|4|Jason|....
4|.....|4|Dan|....
5|.....|4|Robin|....

我需要列出studenttypeid + name上所有重复的记录。

使用上述数据,查询应该给我以下输出:

1|.....|4|Jason|....
2|.....|4|Robin|....
3|.....|4|Jason|....
5|.....|4|Robin|....

如何在SQL Server 2008上实现此目的?

4 个答案:

答案 0 :(得分:1)

您可以使用group by然后再联接回原始表,如下所示:

WITH Temp(StudentTypeId, Name) AS(
    SELECT 
        StudentTypeId, Name
    FROM YourTable
    GROUP BY 
        StudentTypeId, Name
    HAVING Count(1) > 1
)

SELECT YourTable.*
FROM YourTable
INNER JOIN Temp
    ON YourTable.StudentTypeId = Temp.StudentTypeId
    AND YourTable.Name = Temp.Name

答案 1 :(得分:0)

您可以使用ROW_NUMBER()

SELECT ID, DATE, studenttypeid, name, audituser
FROM
(
    SELECT ID, DATE, studenttypeid, name, audituser,
           ROW_NUMBER() OVER (PARTITION BY studenttypeid, name
                              ORDER BY id) rn
    FROM   yourTableName
) a
WHERE  rn = 1

答案 2 :(得分:0)

如果要包含重复项的每个匹配项,请使用CROSS APPLY ...

的其他方法
SELECT p.*
FROM people p
CROSS APPLY (
    SELECT TOP(1) * FROM people p2 WHERE p2.ID <> p.ID AND p2.name = p.name AND p.studenttypeid = p2.studenttypeid
) as pWithDups

或EXISTS检查

SELECT p.*
FROM people p
WHERE EXISTS (
    SELECT * 
    FROM people p2 
    WHERE p2.ID <> p.ID AND p2.name = p.name AND p.studenttypeid = p2.studenttypeid
)

答案 3 :(得分:0)

试试这个

SELECT a.*
FROM   yourtable a
JOIN   (SELECT studenttypeid,
               name
        FROM   yourtable
        GROUP  BY studenttypeid,
                  name
        HAVING Count(studenttypeid) > 1) b ON b.name = a.name
ORDER  BY a.id