本文介紹了如何在 MySQL 中執行分組排名的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
所以我有一個表格如下:
So I have a table as follows:
ID_STUDENT | ID_CLASS | GRADE
-----------------------------
1 | 1 | 90
1 | 2 | 80
2 | 1 | 99
3 | 1 | 80
4 | 1 | 70
5 | 2 | 78
6 | 2 | 90
6 | 3 | 50
7 | 3 | 90
然后我需要對它們進行分組、排序和排序:
I need to then group, sort and order them to give:
ID_STUDENT | ID_CLASS | GRADE | RANK
------------------------------------
2 | 1 | 99 | 1
1 | 1 | 90 | 2
3 | 1 | 80 | 3
4 | 1 | 70 | 4
6 | 2 | 90 | 1
1 | 2 | 80 | 2
5 | 2 | 78 | 3
7 | 3 | 90 | 1
6 | 3 | 50 | 2
現在我知道你可以使用臨時變量來進行排名,像這里,但我如何為分組集做這件事?感謝您的任何見解!
Now I know that you can use a temp variable to rank, like here, but how do I do it for a grouped set? Thanks for any insight!
推薦答案
SELECT id_student, id_class, grade,
@student:=CASE WHEN @class <> id_class THEN 0 ELSE @student+1 END AS rn,
@class:=id_class AS clset
FROM
(SELECT @student:= -1) s,
(SELECT @class:= -1) c,
(SELECT *
FROM mytable
ORDER BY id_class, id_student
) t
這很簡單:
- 初始查詢按
id_class
先排序,id_student
第二排序. @student
和@class
被初始化為-1
@class
用于測試是否輸入了下一組.如果id_class
的先前值(存儲在@class
中)不等于當前值(存儲在id_class
中),@student
被歸零.否則遞增.@class
被賦值為id_class
的新值,它將在下一行的第 3 步的測試中使用.
- Initial query is ordered by
id_class
first,id_student
second. @student
and@class
are initialized to-1
@class
is used to test if the next set is entered. If the previous value of theid_class
(which is stored in@class
) is not equal to the current value (which is stored inid_class
), the@student
is zeroed. Otherwise is is incremented.@class
is assigned with the new value ofid_class
, and it will be used in test on step 3 at the next row.
這篇關于如何在 MySQL 中執行分組排名的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!