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

后端 未结 7 633
醉酒成梦
醉酒成梦 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:28

    OMG Ponie's ROW_NUMBER method is the one that will work best in all scenarios as it will not fail in the event of having two MAX values with the same amount returning more records than expected and breaking a possible insert you might have being fed by that recordset.

    One thing that is missing is how to do it in the event of having to return the subkey associated to each max value, when there are also multiple keys. Simply join your summary table with a MIN and GROUP "itself" and off you go.

    WITH summary AS (
      SELECT t.*,
             ROW_NUMBER() OVER(ORDER BY t.subkey DESC) AS rank
        FROM TABLE t
       WHERE t.key = 1)
    SELECT s.*
      FROM summary s
      join  (select key, min(rank) as rank
            from summary
            group by key) sMAX
            on s.key = sMAX.key and r.rank = sMAX.rank
    

提交回复
热议问题