how to select only row with max sequence without using a subquery?

后端 未结 3 1954
误落风尘
误落风尘 2020-12-30 09:38

I\'m trying to select only the row with the highest seq for each ID

ID  |  Seq   |  Age
-------------------
 A      1       20   
 A      2       30
 B               


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 09:52

    In general, you neeed to use windowing or ranking functions - Rank(), Row_number(), etc.

    select *
    from
    (
        select *, row_number() over (partition by id order by age desc) rn
        from yourtable
    ) v
    where rn = 1
    

    This will work in SQL Server 2005+ - in oracle you may need to specify the field names explicitly, instead of the *

提交回复
热议问题