SQL:如何从重复行中选择第一条记录?

时间:2018-03-25 10:51:53

标签: sql sql-server tsql duplicates

执行以下查询以查找重复的

select * from (
select a.* ,count (*) over (partition by a.ID) as tot
from HREMP a 
) tt
where tt.tot >1

返回423行,

我执行了另一个查询来查找非重复记录

  select * from (
select a.* ,count (*) over (partition by a.ID) as tot
from HREMP a 
) tt
where tt.tot =1

返回685条记录

  

我发现423个副本中有196个不同的记录   现在,如何从重复记录中选择第一条记录?

1 个答案:

答案 0 :(得分:5)

select distinct * 
from ( select a.*, count(*) over (partition by a.ID) as tot
       from HREMP a 
     ) tt
where tt.tot > 1

select * 
from ( select a.*
            , count(*)     over (partition by a.ID) as tot
            , row_number() over (partition by a.ID order by 1) as rn
       from HREMP a 
     ) tt
where tt.tot > 1 
and   tt.rn = 1