【问题标题】:SQL:How to select the first record from duplicate rows?SQL:如何从重复行中选择第一条记录?
【发布时间】:2018-09-03 15:01:33
【问题描述】:

在执行以下查询以查找重复项时

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 个不同的记录 现在,如何从重复记录中选择第一条记录?

【问题讨论】:

  • 如何判断哪个是第一条记录?按 HREMP_ID?
  • 是的..@anonyXmous

标签: sql sql-server tsql duplicates


【解决方案1】:
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

【讨论】:

  • 我已经准备好进行第二次查询,但第一次查询让我感到非常惊讶,distinct * .. 谢谢你..
  • 你可以检查它是否回答了你的问题
  • 我试了两次,但需要再等 4 分钟.. woaa
  • 您不需要使用 count(*),因为 row_number() 也会在 ID 唯一的情况下分配值 1。
  • 使用 DISTINCT 会降低执行性能。这可以通过使用 row_number() 之类的分析窗口函数来避免。
猜你喜欢
  • 2012-04-23
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 2022-01-19
相关资源
最近更新 更多