Retrieving Records with Max Values using TOP

I know I know, it’s a horrible title. If anyone has a better suggestion please let me know!

Here’s what I’m talking about:

I have two tables; the first table contains unique records describing games and the second contains game ids, scores, and user ids. Game id is joining the first table to the second in a one to many, something like this:

Games
======
gameID
gameName

GameScores
=========
gameID
userID
score

MY MISSION: Retrieve the user with the high score for each game in one query.

After much trial, error, and gnashing of teeth, the solution, as usual, proved to be ridiculously simple:


SELECT (select top 1 userID from GameScores where gameID = Games.gameID order by score desc) as topScoreUser,
                Games.gameName,Games.gameID, s.score
FROM Games
JOIN   GameScores s on s.gameID = Games.gameID

What this does is return one record for each game. Since I’m only returning the top record in the query and I’m ordering by score in descending order, I’m getting the top score and player for each game.

I’ve run into quite a few instances now where TOP has proved invaluable. Unfortunately it always seems to take me an hour of futzing around before I remember to use it!

-rG