删除重复的行并保留一行

时间:2012-03-23 19:01:40

标签: sql-server sql-server-2008 tsql

这是我的表Result_Simul的名称

这是值

       Pk   FkIdResult   FkIdSimul
       1        43         1244
       2        43         1244
       3        52         1244
       4        52         1244

如何保持行Pk = 1和Pk = 3并删除Pk = 2和Pk = 4

感谢您的帮助。

我在Tsql中并不是很好

弗兰克

2 个答案:

答案 0 :(得分:12)

您可以使用row_number为每个副本提供一个升序号码,然后删除第二个和更高的重复项:

delete  tbl
from    (
        select  row_number() over (partition by FkIdResult, FkIdSimul 
                                  order by Pk desc) as rn
        ,       *
        from    YourTable
        ) tbl
where   rn > 1

Working example at SE Data.

答案 1 :(得分:-1)

在mysql中:

create temporary table table2 as (select min(pk) as pk from Table1 group by FkIdResult   );     
delete from Table1 where pk not in (select pk from table2)