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
This will return all the values with subkey values that match, in case there are multiples.
SELECT a.value
FROM TABLE a
JOIN (SELECT MAX(t.subkey) AS max_subkey
FROM TABLE t
WHERE t.key = 1) b ON b.max_subkey = a.subkey
WHERE a.key = 1
This will return all the values with subkey values that match, in case there are multiples.
WITH summary AS (
SELECT t.*,
RANK() OVER(ORDER BY t.subkey DESC) AS rank
FROM TABLE t
WHERE t.key = 1)
SELECT s.value
FROM summary s
WHERE s.rank = 1
This will return one row, even if there are more than one with the same subkey value...
WITH summary AS (
SELECT t.*,
ROW_NUMBER() OVER(ORDER BY t.subkey DESC) AS rank
FROM TABLE t
WHERE t.key = 1)
SELECT s.value
FROM summary s
WHERE s.rank = 1
This will return one row, even if there are more than one with the same subkey value...
SELECT TOP 1
t.value
FROM TABLE t
WHERE t.key = 1
ORDER BY t.subkey DESC