I have a query that ranks results in MySQL:
SET @rank := 0;
SELECT Name, Score, @rank := @rank + 1
FROM Results
ORDER BY Score
This works fine until I try to base the ranking on the average score:
SET @rank := 0;
SELECT Name, AVG(Score) as AvScore, @rank := @rank + 1
FROM Results
ORDER BY AvScore
If I run this I get just the one record back because of the AVG. However, if I add a GROUP BY on Name so that I can get the averages listed for everyone, this has the effect of messing up the correct rankings.
I know the answer’s probably staring me in the face but I can’t quite get it. How can I output a ranking for each name based on their average result?
You need to use a sub-query: