如何在SQL表中找到重复记录

时间:2013-09-09 06:05:56

标签: sql sql-server sql-server-2008-r2

我有一张近20000条记录的桌子 用列

Id      SubjectId      UniqueId
1        54            1
1        58            2
1        59            3
1        60            4
2        54            5
2        58            6
2        59            7
2        60            8
2        60            9
3        54            10
3        70            11

我想选择那些重复的记录 像
结果就像

Id      SubjectId      UniqueId
 2        60            8
 2        60            9
 7        54            15
 7        54            18
 7        54            30

帮帮我怎么做呢

4 个答案:

答案 0 :(得分:8)

使用EXISTS()

SELECT  a.*
FROM    tableName a
WHERE   EXISTS
        (
            SELECT  1
            FROM    tableName b
            WHERE   a.ID = b.ID AND
                    a.SubjectID = b.subjectID
            GROUP   BY Id, SubjectId
            HAVING  COUNT(*) > 1
        )

答案 1 :(得分:1)

您可以使用分析COUNT(),因为您使用的是 SQL Server 2008

SELECT id, subjectid, uniqueid
  FROM   
(
  SELECT  id, subjectid, uniqueid,
          COUNT(*) OVER (PARTITION BY id, subjectid) cnt
    FROM  table1
) q
 WHERE cnt > 1

或其他方式

SELECT t.*
  FROM   
(
  SELECT  id, subjectid
    FROM  table1
   GROUP  BY id, SubjectId
  HAVING  COUNT(*) > 1
) q JOIN table1 t
    ON q.id = t.id
   AND q.subjectid = t.subjectid

两个查询的输出:

| ID | SUBJECTID | UNIQUEID |
|----|-----------|----------|
|  2 |        60 |        8 |
|  2 |        60 |        9 |
|  7 |        54 |       15 |
|  7 |        54 |       18 |
|  7 |        54 |       30 |

这是 SQLFiddle 演示

答案 2 :(得分:1)

试试这个

仅获取重复记录

SELECT * FROM TABLE_NAME as t1 where SubjectId  in (SELECT SubjectId   FROM TABLE_NAME as t2 where t2.Id=t1.Id and t1.UniqueId<>t2.UniqueId) order by Id,SubjectId   

答案 3 :(得分:0)

计算您的ID,如果大于1,则选择它

SELECT  *
FROM    table
HAVING  COUNT(id) > 1