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

后端 未结 3 1929
误落风尘
误落风尘 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

    Assuming SQL-Server ( >= 2005) or Oracle (10g?):

    WITH CTE AS
    ( 
       SELECT
           ROW_NUMBER() OVER (PARTITION BY ID  ORDER BY Seq DESC) AS RN
           , ID, Age
       FROM 
           Persons
    )
    SELECT ID, Age 
    FROM CTE
    WHERE RN = 1
    

    ROW_NUMBER returns the sequential number of a row within a partition of a result set.

    Edit: works also in Oracle as you can see here: http://sqlfiddle.com/#!4/b7e79/2/0

提交回复
热议问题