简体   繁体   English

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

[英]combining two sql queries in one statement

l have a list of students score, i want to find the rank for each student according to his average 我有一个学生成绩列表,我想根据他的平均水平找到每个学生的排名

here is the table 这是桌子 在此处输入图片说明

steps to find the student rank. 查找学生等级的步骤。

  1. create the view of average score for each student 创建每个学生的平均分数视图

      CREATE VIEW mid_view as SELECT *,AVG(score) as score from midterm_result group by student_id 

在此处输入图片说明

2.. find the rank 2 ..找到等级

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

result is 结果是 在此处输入图片说明

my target is to reduce the steps, i want to reach at final result without creating the mid_view 我的目标是减少步骤,我想在不创建mid_view的情况下达到最终结果

How can i combine these to queries in single statement? 如何将这些合并到单个语句中的查询?

You could just include the first query as a sub query of the second one: 您可以只将第一个查询作为第二个查询的子查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM