0

我有一个查询在 MySQL 中对结果进行排名:

SET @rank := 0;
SELECT Name, Score, @rank := @rank + 1 
FROM Results 
ORDER BY Score

在我尝试将排名基于平均分数之前,这很好用:

SET @rank := 0;
SELECT Name, AVG(Score) as AvScore, @rank := @rank + 1 
FROM Results 
ORDER BY AvScore

如果我运行它,由于 AVG,我只会得到一条记录。但是,如果我在 Name 上添加一个 GROUP BY 以便我可以列出每个人的平均值,这会影响正确的排名。

我知道答案可能正盯着我看,但我不太明白。如何根据平均结果为每个名称输出排名?

4

2 回答 2

3

您需要使用子查询:

SET @rank := 0;

SELECT a.name, 
       a.avscore, 
       @rank := @rank + 1 
FROM   (SELECT name, 
               Avg(score) AS AvScore 
        FROM   results 
        GROUP  BY name) a
ORDER  BY a.avscore 
于 2013-02-07T18:57:53.887 回答
1

您必须先订购,然后从派生表中选择排名:

SELECT Name, AvScore, @rank := @rank + 1
FROM (
    SELECT Name, AVG(AvScore) AS AvScore FROM Results 
    GROUP BY Name ORDER BY AVG(AvScore)
) t1, (SELECT @rank = 0) t2;
于 2013-02-07T19:02:54.183 回答