自联接查询以查找重复记录

时间:2015-06-30 10:27:42

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

我有一个包含大约32列的表,我想检查重复的行,但是两列是唯一的,因此每行的它们都不同。所以我需要JOIN条件基本上自我加入重复记录,其中所有列都相等,除了两个。

2 个答案:

答案 0 :(得分:4)

要查找重复的行,查询将是(col1 ... col30将排除每行始终唯一的两列)

SELECT
  col1,
  col2,
  ...,
  col30
FROM
  your_table
GROUP BY
  col1,
  col2,
  ...,
  col30
HAVING
  COUNT(*)>1

编辑:从您要删除重复行的备注中显示。假设您有列id1和id2,这些列对于每一行(即主键)和列col1..col4都是唯一的,可以重复。以下面的脚本为例删除重复的行:

CREATE TABLE #tt(
    id1 INT,
    id2 INT,
    col1 INT,
    col2 INT,
    col3 INT,
    col4 INT,
    PRIMARY KEY(id1,id2)
);

INSERT INTO #tt(id1,id2,col1,col2,col3,col4)
VALUES (1,1,1,1,1,1),
       (1,2,1,1,1,1),
       (1,3,1,1,1,1),
       (2,1,1,1,1,1),
       (3,1,2,2,2,2),
       (4,1,2,2,2,2),
       (2,2,2,2,2,2),
       (3,3,3,3,3,3),
       (4,2,3,3,3,3);

DELETE
    t
FROM
    #tt AS t
    INNER JOIN (
        SELECT
            id1,
            id2,
            ROW_NUMBER() OVER (PARTITION BY col1,col2,col3,col4 ORDER BY id1,id2) AS rn
        FROM
            #tt
    ) AS trn ON
        trn.id1=t.id1 AND
        trn.id2=t.id2
WHERE
    trn.rn>1;

SELECT*FROM #tt;

DROP TABLE #tt;

答案 1 :(得分:0)

您也可以使用以下内容:

SELECT *
FROM yourTable t
WHERE 1 < (
    SELECT COUNT(*) 
    FROM yourTable ti
    WHERE t.uniqueCol1 = ti.uniqueCol1 AND t.uniqueCol2 = ti.uniqueCol2
    GROUP BY nonUniqueCol1, nonUniqueCol2, ..., nonUniqueColn)

或仅过滤重复的行而不显示您可以使用的原始行:

SELECT *
FROM (SELECT *,
          ROW_NUMBER() OVER (PARTITION BY nonUniqueCol1, nonUniqueCol2, ..., nonUniqueColn
                             ORDER BY uniqueCol1, uniqueCol2) As seq
      FROM yourTable) t
WHERE (seq > 1)