MS SQL - 查找和删除重复项

时间:2011-12-09 08:16:50

标签: sql sql-server

  

可能重复:
  SQL - How can I remove duplicate rows?
  SQL query to delete duplicate rows from same table?

如何在此表中找到双重性?

enter image description here

A 是唯一ID,列 E F 无关,所以行1,2,3 和行 4,5 是重复的

4 个答案:

答案 0 :(得分:2)

我有一个更有效的解决方案:

DELETE FROM MyTable 
    WHERE A NOT IN 
        (SELECT MIN(A) 
         FROM MyTable GROUP BY B, C, D
        );

注意:如果“A”不为NULL,则此方法有效。因此,对于某些类似的任务,它无济于事。

答案 1 :(得分:1)

select MyTable.A 
from MyTable 
     join (select B,C,D 
           from MyTable 
           group by B,C,D 
           having Count(*)>1) as T2 on MyTable.B = T2.B 
                                       and MyTable.C = T2.C 
                                       and MyTable.D = T2.D

答案 2 :(得分:1)

尝试:

<强> select count(A) Occurrence, B, C, D from TableName group by B, C, D having count(A) > 1

要获取重复列的ID,请使用:

<强> select A from TableName where (B + ' ' + C + ' ' + D) in (select B + ' ' + C + ' ' + D from TableName group by B, C, D having count(A) > 1)

答案 3 :(得分:1)

请尝试以下查询:

WITH CustomTable
 AS (SELECT  B, C, D, ROW_NUMBER() OVER (PARTITION BY B, C, D 
                                   ORDER BY ( SELECT 0)) RowNumber
     FROM   TableName)
DELETE FROM CustomTable
WHERE  RowNumber > 1