使用AVG排序mysql查询的结果

时间:2013-02-07 18:55:55

标签: mysql

我有一个在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以便我可以获得为每个人列出的平均值,则会产生混乱正确排名的效果。

我知道答案可能正在盯着我,但我无法理解。如何根据平均结果为每个名称输出排名?

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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;