Delete duplicate lines and keep one line

This is the name of my table Result_Simul

This value

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

How to save the rows Pk = 1 and Pk = 3 and delete Pk = 2 and Pk = 4

Thanks for helping me.

Im not very good in Tsql

Frank

+5
source share
2 answers

You can use row_numbereach duplicate to increase the number and then delete the second 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

Working example in SE data.

+12
source

in 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)
-1
source

All Articles