我可以删除基于多列的数据库副本吗?

时间:2012-07-23 14:32:24

标签: sql-server database

asked this question a while back根据列删除重复记录。答案很有效:

delete from tbl
where id NOT in
(
select  min(id)
from tbl
group by sourceid
)

我现在有一个类似的情况,但重复记录的定义基于多个列。如何更改上面的SQL以识别重复记录,其中唯一记录定义为从Col1 + Col2 + Col3连接。我会做这样的事吗?

delete from tbl
where id NOT in
(
select  min(id)
from tbl
group by col1, col2, col3
)

2 个答案:

答案 0 :(得分:25)

这显示了您要保留的行:

;WITH x AS 
(
  SELECT col1, col2, col3, rn = ROW_NUMBER() OVER 
      (PARTITION BY col1, col2, col3 ORDER BY id)
  FROM dbo.tbl
)
SELECT col1, col2, col3 FROM x WHERE rn = 1;

显示您要删除的行:

;WITH x AS 
(
  SELECT col1, col2, col3, rn = ROW_NUMBER() OVER 
      (PARTITION BY col1, col2, col3 ORDER BY id)
  FROM dbo.tbl
)
SELECT col1, col2, col3 FROM x WHERE rn > 1;

一旦你对以上两组是正确的感到高兴,以下实际上会删除它们:

;WITH x AS 
(
  SELECT col1, col2, col3, rn = ROW_NUMBER() OVER 
      (PARTITION BY col1, col2, col3 ORDER BY id)
  FROM dbo.tbl
)
DELETE x WHERE rn > 1;

请注意,在所有三个查询中,前6行是相同的,只有CTE更改后的后续查询。

答案 1 :(得分:4)

试试这个。 我用三列创建了一个表 tblA

CREATE TABLE tblA
(
id int IDENTITY(1, 1),
colA int, 
colB int, 
colC int
)

并添加了一些重复值。

INSERT INTO tblA VALUES (1, 2, 3)
INSERT INTO tblA VALUES (1, 2, 3)
INSERT INTO tblA VALUES (4, 5, 6)
INSERT INTO tblA VALUES (7, 8, 9)
INSERT INTO tblA VALUES (7, 8, 9)

如果您在下面的语句中将删除替换为删除,则可以使多列删除工作。

SELECT MIN(Id) as id
FROM
(
SELECT COUNT(*) as aantal, a.colA, a.colB, a.colC
FROM tblA       a
INNER JOIN tblA b   ON b.ColA = a.ColA
                    AND b.ColB = a.ColB
                    AND b.ColC = a.ColC
GROUP BY a.id, a.colA, a.colB, a.colC
HAVING COUNT(*) > 1
) c
INNER JOIN tblA d ON d.ColA = c.ColA
                    AND d.ColB = c.ColB
                    AND d.ColC = c.ColC
GROUP BY d.colA, d.colB, d.colC