如何从SQL Server中的列表中获取第一条记录

时间:2014-04-09 18:32:00

标签: sql sql-server

我希望得到一个记录列表,其中GLOBALID是唯一的,基于最后一列的MAX

e.g。数据

GLOBALID   FIRST  SECOND  FINAL
-------------------------------
00345       867    --      8976
00345       989    567     5674
00356       765    554     5658
00359       ---    543     7567

结果应该是..

GLOBALID  FIRST  SECOND  FINAL
-------------------------------
00345      867    --     8976
00356      765    554    5658
00359      ---    543    7567

2 个答案:

答案 0 :(得分:1)

select t1.*
from your_table t1
join
(
  select globalid, max(final) as m_final
  from your_table
  group by globalid
) t2 on t1.globalid = t2.globalid and t1.final = t2.m_final

答案 1 :(得分:0)

select t1.*
from (
  select yt.*, 
         max(final) over (partition by globalid) as m_final
  from your_table
) t1
where t1.final = t1.m_final;

如果“最大值”出现多次,您仍可能每globalid行获得一行以上。为防止这种情况,您可以使用row_number()

select t1.*
from (
  select yt.*, 
         row_number() over (partition by globalid order by final desc) as rn
  from your_table
) t1
where rn = 1;