删除重复的行

时间:2012-05-24 16:17:16

标签: sql-server-2008 duplicate-removal

我需要删除所有重复的行:

t1
--------------------
col1    col2    col3
1       a       b
2       a       c
3       a       b

在此示例中,1和3是重复的。我需要将两者都插入到另一个表中,然后从当前表中删除它们。

t1
--------------------
col1    col2    col3
1       a       c

t2
--------------------
col1    col2    col3
1       a       b
2       a       b

这样做的最佳方式是什么?

修改

我应该提供更多信息。 t1是包含导入行的临时表。有4个字段唯一标识记录,每行另外20个字段。如果存在重复项,则需要将它们插入到不同的表中以供查看。因此,我不相信身份值需要保留,因为一旦它插入到系统中,临时表中的值将不再有用。

5 个答案:

答案 0 :(得分:0)

以下代码可用于删除重复记录。该表必须具有标识列,该标识列将用于标识重复记录。示例中的表具有ID作为标识列,具有重复数据的列是DuplicateColumn1,DuplicateColumn2和DuplicateColumn3。

DELETE
FROM MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn3)

引自:http://blog.sqlauthority.com/2007/03/01/sql-server-delete-duplicate-records-rows/

答案 1 :(得分:0)

查找所有重复行的一种方法是将表连接到可能具有重复数据的所有列上,并过滤掉col1值相同的行,如下所示:

select distinct a.col1
from t1 a inner join t1 b on a.col2 = b.col2 and a.col3 = b.col3
where a.col1 <> b.col1

您可以使用它来从t1插入t2(根据我对你的问题的评论,假设你想在t2中保留t1的col1值):

insert into t2 (col1, col2, col3)
select col1, col2, col3
from t1
where col1 in (
    select distinct a.col1
    from t1 a inner join t1 b on a.col2 = b.col2 and a.col3 = b.col3
    where a.col1 <> b.col1
)

然后从t1删除

delete t1
where col1 in (
    select distinct a.col1
    from t1 a inner join t1 b on a.col2 = b.col2 and a.col3 = b.col3
    where a.col1 <> b.col1
)

通过使用临时表来保存col1值可以使这更简单,这样您就不必再次进行自联接。使用临时表也会更安全。通过两个单独的查询,每个查询都进行自连接,可以(远程)从t1中删除行而不将它们插入到t2(即,如果在执行插入到t2和从t1删除之间,新的重复项被写入t1,新插入的行到t1将在第二个自连接中匹配。

此外,对于删除,您可以使用t2而不是再次在t1上进行自联接(同样,如果我的假设是正确的并且您在t2中保留了col1值)。

答案 2 :(得分:0)

INSERT INTO T2(Col2, Col3)
SELECT Col2, Col3
FROM T1
WHERE EXISTS (  SELECT * 
                FROM T1 AS T 
                WHERE   T.Col2 = T1.Col2
                    AND T.Col3 = T1.Col3
                    AND T.Col1 <> T1.Col1
            )

DELETE FROM T1 
WHERE EXISTS (  SELECT * 
                FROM T2 
                WHERE   T2.Col2 = T1.Col2
                    AND T2.Col3 = T1.Col3
            )

答案 3 :(得分:0)

搞定了。

将所有重复记录插入t2。

insert into t2
select src.col2, src.col3 from t1 src
inner join (select t1.col2, t1.col3 from t1
            group by t1.col2, t1.col3
            having count(*) > 1) duplicates 
on src.col2 = duplicates.col2 and src.col3 = duplicates.col3

从t1删除重复项。

delete from t1
where t1.col1 in (
    select src.col1 from t1 src
        inner join (
                    select t1.col2, t1.col3 from t1
                    group by t1.col2, t1.col3
                    having count(*) > 1) duplicates
                    on src.col2 = duplicates.col2 and src.col3 = duplicates.col3
                   )
)

答案 4 :(得分:0)

Select * into temp(temporary table) 
 from tablename 
       group by column_name1,column_name2 
         having (count(*)>=1)

---将数据插入到临时表中,没有任何重复数据

drop tablename

select * into Tablename from temp