删除重复行并保留一行

2021-09-10 00:00:00 tsql sql-server-2008 sql-server

这是我的表 Result_Simul 的名称

This the name of my table 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

How to keep just keep rows Pk=1 and Pk=3 and delete Pk=2 and Pk=4

谢谢你帮助我.

我不太擅长 Tsql

弗兰克

推荐答案

您可以使用 row_number 为每个重复项赋予一个升序编号,然后删除第 2 个及更高的重复项:

You can use row_number to give each duplicate an ascending number, and then delete the 2nd and higher duplicates:

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

SE Data 的工作示例.

相关文章