T-SQL: Selecting Column Based on MAX(Other Column)

后端 未结 7 699
醉酒成梦
醉酒成梦 2020-11-27 12:06

I\'m hoping there\'s a simple way to do this without using a sub-query:

Scenario: You have \"TableA\" with columns \"Key\", \"SubKey\", and \"Value\". I need to ge

7条回答
  •  一向
    一向 (楼主)
    2020-11-27 12:32

    OMG Ponies hit most of the ways to do it. Here's one more:

    SELECT
        T1.value
    FROM
        My_Table T1
    LEFT OUTER JOIN My_Table T2 ON
        T2.key = T1.key AND
        T2.subkey > T1.subkey
    WHERE
        T2.key IS NULL
    

    The only time that T2.key will be NULL is when there is no match in the LEFT JOIN, which means that no row exists with a higher subkey. This will return multiple rows if there are multiple rows with the same (highest) subkey.

提交回复
热议问题