Get Max Date for Group and it's Associated Record ID

  • I have a table that looks like the below (sorry for the horrible formatting).

    ID | Class | Date

    ----------------------------------

    1 | Class A | 1/1/16

    2 | Class A | 2/1/16

    3 | Class A | 3/1/16

    4 | Class B | 4/1/16

    5 | Class C | 5/1/16

    I want to find records with the maximum date for each 'Class' group, but I need to know the ID's for each group. So a basic GROUP BY query won't do it.

    This is what I want it to return.

    ID | Class | Date

    ----------------------------------

    3 | Class A | 3/1/16

    4 | Class B | 4/1/16

    5 | Class C | 5/1/16

  • For a newb, nice job posting!

    This should do it... you might want to play with ROW_NUMBER() for a while... super handy once you figure out how it works.

    SELECT y.Class

    , y.ID

    , y.ClassDate

    , y.rn

    FROM

    (SELECT Class,

    ID,

    ClassDate,

    ROW_NUMBER() OVER (PARTITION BY Class ORDER BY Class, ClassDate DESC) AS rn

    FROM

    (

    SELECT 1 AS ID, 'Class A' AS Class, '1/1/16' AS ClassDate

    UNION ALL

    SELECT 2 , 'Class A' , '2/1/16'

    UNION ALL

    SELECT 3 , 'Class A' , '3/1/16'

    UNION ALL

    SELECT 4 , 'Class B' , '4/1/16'

    UNION ALL

    SELECT 5 , 'Class C' , '5/1/16'

    ) x ) y

    WHERE y.rn = 1;

  • Wow... so.. um... yeah. I don't understand how that works, but it works!

    Thanks a lot for your help!

    I'll have to study this one.

    Didn't know you could do two "FROM" statements

  • Oh wait duh. I see it now. It's two nested sub-queries. Anyway... still great stuff and will have to study the ROW_NUMBER() function.

    Thank you! Thank you!

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply