Max and Group By

  • CREATE TABLE [temp](

    [id] [int] NOT NULL,

    [seq] [int] NOT NULL,

    [date] [int] NOT NULL,

    [value] [int] NULL,

    CONSTRAINT [PK_temp] PRIMARY KEY CLUSTERED ([id] ASC,[seq] ASC))

    INSERT INTO [temp]

    ([id],[seq],[date],[value])

    VALUES

    (1,1,2012,2),(1,2,2012,4),(1,3,2013,3),(1,4,2013,2),(1,5,2013,4),

    (2,1,2014,4),(3,1,2014,4),(4,1,2014,4)

    I want to write a query that get records have max(date) and group by [id]

    Select top 1 if max(date) the same.

    result:

    id date value

    1 2013 3

    2 2014 4

    3 2014 4

    4 2014 4

    Pls help me. Thanks

  • Try this:

    SELECT id, date, [value]

    FROM (

    SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY id, date DESC) AS rk

    FROM [temp]

    ) x

    WHERE rk = 1


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • dwain.c (2/28/2012)


    Try this:

    SELECT id, date, [value]

    FROM (

    SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY id, date DESC) AS rk

    FROM [temp]

    ) x

    WHERE rk = 1

    Thanks dwain.c

    It's working fine for me.

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

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