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
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