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 get the "Value" of the MAX("SubKey") for a given "Key".
So if the Table contained the rows:
KEY SUBKEY VALUE
1 1 100
1 2 200
1 3 300
For Key = 1, I need the value 300. I was hoping to do something like this:
SELECT
VALUE
FROM
TableA
WHERE
Key = 1
HAVING
SubKey = MAX(SubKey)
But that's a no-go. Is there a way to do this without doing a 'WHERE SubKey = (subselect for max subkey)'?
In case of multiple keys using a CTE:
Using a self join:
This will return all the values with subkey values that match, in case there are multiples.
Using RANK & CTE (SQL Server 2005+):
This will return all the values with subkey values that match, in case there are multiples.
Using ROW_NUMBER & CTE (SQL Server 2005+):
This will return one row, even if there are more than one with the same subkey value...
Using TOP:
This will return one row, even if there are more than one with the same subkey value...
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 twoMAX
values with the same amount returning more records than expected and breaking a possible insert you might have being fed by thatrecordset
.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 aMIN
andGROUP
"itself" and off you go.Very simple, no join, no sub-query:
If you need max value for each Key:
If you'll always want just one row for one key value rather than the answer for many keys at once, all the join stuff is useless overbuilding. Just use the TOP 1 query OMG Ponies already gave you.