我有一个学生得分列表,我想根据他的平均值找到每个学生的等级
这是表格
找到学生排名的步骤。
创建每个学生的平均分数视图
CREATE VIEW mid_view as
SELECT *,AVG(score) as score from midterm_result group by student_id
2 ..找到等级
SELECT * , @rank := if( @last = average, @rank , @seq ) AS rank, @seq := @seq +1,
@last := average
FROM mid_view
ORDER BY average DESC
结果是
我的目标是减少步骤,我希望在不创建 mid_view 的情况下达到最终结果
如何在单个语句中将这些结合到查询中?
答案 0 :(得分:3)
您可以将第一个查询包含为第二个查询:
SELECT m.*, @rank := if(@last = average, @rank, @seq) AS rank,
@seq := @seq +1, @last := average
FROM
(
SELECT *, AVG(score) as score
from midterm_result
group by student_id
) m
ORDER BY average DESC