SQL Server: how to imitate oracle keep dense_rank query?

前端 未结 5 1936
既然无缘
既然无缘 2020-12-20 17:46

I have an Oracle query

select max(m.id),
       m.someId keep (DENSE_RANK FIRST ORDER BY m.UpdateDate desc) 
from MyTable m 
groupBy m.someId
5条回答
  •  佛祖请我去吃肉
    2020-12-20 17:55

    SQL Server does not support the "keep" construct, so you need to use a subquery:

    select m.*
    from (select *, row_number() over (partition by m.someid ORDER BY m.UpdateDate desc) as seqnum
          from MyTable m
         ) m
    where seqnum = 1
    

    This finds the first row for each m.id with the most recent UpdateDate. It then chooses that row in the outer query. Note that you don't need a group by with this method.

提交回复
热议问题