简体   繁体   中英

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

     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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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