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

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

    0 讨论(0)
  • 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 *

    0 讨论(0)
  • 2020-12-30 10:05

    Just in case you use an RDBMS that doesn't support window functions, you can use:

    SELECT  Persons.ID, Persons.Age, Persons.Seq
    FROM    Persons
            INNER JOIN
            (   SELECT  Persons.ID, MAX(Seq) AS Seq
                FROM    Persons
                GROUP BY Persons.ID
            ) MaxP
                ON MaxP.ID = Persons.ID
                AND MaxP.Seq = Persons.Seq
    

    It still involves a subquery, but I don't see a way of doing this without one, nor do I really understand why you would want to avoid them.

    0 讨论(0)
提交回复
热议问题