SELECT a.s_id, @i:=@i+1 AS i, -- @k:=(case when @score=a.sum_score then @k else @i end) as rank, a.sum_score AS score FROM (SELECT s_id,SUM(s_score) AS sum_score FROM score GROUP BY s_id ORDER BY sum_score DESC)a, (SELECT @k:=0,@i:=0,@score:=0)s
时间: 2023-03-19 08:23:25 浏览: 151
This is a MySQL query that selects the student ID (s_id), assigns a sequential number to each row (i), and calculates the rank of each student based on their sum of scores (sum_score).
The query uses a subquery to first group the scores by student ID and calculate the sum of scores for each student. This subquery is then joined with a variable initialization subquery that sets the initial values of @k, @i, and @score to 0.
The variable @k is used to keep track of the current rank while iterating over the rows. The variable @i is used to assign a sequential number to each row. The variable @score is used to compare the sum_score of the current row with the sum_score of the previous row.
The CASE statement is used to check if the sum_score of the current row is equal to the sum_score of the previous row. If they are equal, then the rank remains the same. If they are not equal, then the rank is updated to the current sequential number.
Here is a breakdown of the query:
```
SELECT
a.s_id, -- Select the student ID
@i:=@i+1 AS i, -- Assign a sequential number to each row
@k:=(case when @score=a.sum_score then @k else @i end) as rank, -- Calculate the rank
a.sum_score AS score -- Select the sum of scores for each student
FROM
(SELECT s_id,SUM(s_score) AS sum_score FROM score GROUP BY s_id ORDER BY sum_score DESC) a, -- Subquery to calculate sum of scores for each student
(SELECT @k:=0,@i:=0,@score:=0) s -- Subquery to initialize variables
```
Note that the use of variables in this query is not recommended, as it can lead to unexpected results if the variables are not reset properly. It is better to use a subquery or a window function to calculate the rank.
阅读全文