PersonID with Max(Version) from it...

  • Hi,

    how can I get effectively max(version) to identify any PersonID with multiple VersionID?

    PersonID version

    1 1

    1 2

    1 3

    2 1

    2 2

    3 1

    4 1

    4 2

    and so on ...

    Result

    1 3

    2 2

    3 1

    4 2

    Thank you

    Nicole

    🙂

  • info 58414 (8/9/2012)


    Hi,

    how can I get effectively max(version) to identify any PersonID with multiple VersionID?

    That's what GROUP BY and MAX are for 🙂

    DECLARE @persons TABLE(

    personid INT,

    version INT)

    INSERT @persons

    VALUES(1,1),(1,2),(1,3),(2,1),(2,2),(3,1),(4,1),(4,2)

    SELECT

    personid,

    maxversion = MAX(version)

    FROM

    @persons

    GROUP BY personid

    ORDER BY personid



    --Mark Tassin
    MCITP - SQL Server DBA
    Proud member of the Anti-RBAR alliance.
    For help with Performance click this link[/url]
    For tips on how to post your problems[/url]

  • Curious, which is the more scalable solution?

    DECLARE @persons TABLE(

    personid INT,

    version INT);

    INSERT @persons

    VALUES(1,1),(1,2),(1,3),(2,1),(2,2),(3,1),(4,1),(4,2);

    SELECT

    personid,

    maxversion = MAX(version)

    FROM

    @persons

    GROUP BY personid

    ORDER BY personid;

    WITH BaseData AS (

    SELECT

    personid,

    version,

    ROW_NUMBER() OVER (PARTITION BY personid ORDER BY version DESC) rn

    FROM

    @persons

    )

    SELECT

    personid,

    version

    FROM

    BaseData

    where

    rn = 1;

    I guess I'll have to test this at home tonight.

  • Looking at the execution plan, group by version looks simplier, 4 operators versus 6. The table scan and sort have the same cost associated in both.

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

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