在一个语句中组合两个sql查询

时间:2014-08-20 17:40:03

标签: mysql sql subquery

我有一个学生得分列表,我想根据他的平均值找到每个学生的等级

这是表格 enter image description here

找到学生排名的步骤。

  1. 创建每个学生的平均分数视图

      CREATE VIEW mid_view as 
      SELECT *,AVG(score) as score from midterm_result group by student_id
    
  2. enter image description here

    2 ..找到等级

         SELECT * , @rank := if( @last = average, @rank , @seq ) AS rank, @seq := @seq +1,   
         @last := average
        FROM mid_view
        ORDER BY average DESC
    

    结果是   enter image description here

    我的目标是减少步骤,我希望在不创建 mid_view 的情况下达到最终结果

    如何在单个语句中将这些结合到查询中?

1 个答案:

答案 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