2011-03-28 169 views
3

我有重复这样SQL Server 2008中删除重复

col1, col2 
1, alex 
1, alex 
2, liza 
2, liza 
3, peter 
3, peter 

只有每两个。我如何删除重复项?

+1

是否有可用的区分各行的任何其他列? – 2011-03-28 15:36:54

+0

@joeyes有一个顺序pK – 2011-03-28 15:37:54

+1

可能的重复的[SQL - 我如何删除重复的行?](http://stackoverflow.com/questions/18932/sql-how-can-i-remove-duplicate-rows) – 2011-03-28 15:41:37

回答

12
WITH q AS 
     (
     SELECT *, 
       ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY col1, col2) AS rn 
     FROM mytable 
     ) 
DELETE 
FROM q 
WHERE rn >= 2 

在这里看到:

+0

+1非常好用的CTE! – 2011-03-28 15:41:37

+3

+1:学到了新东西。我不知道你可以使用CTE作为删除操作的目标。 – 2011-03-28 15:43:56

1

如果源表不是很大。

select distinct * from origin_table into temp_table; 
truncate table origin_table; 
insert into origin_table select * from temp_table ; 
drop table temp_table; 
0
insert into table_new 
    Select col1, col2, min(pk) as pk from table_old 
    group by col1, col2 

-- debug table_new 

drop table_old