mysql 計算排名,生成排行榜

mysql計算排名,獲取行號rownomysql

學生成績表數據

SELECT * FROM table_score ORDER BY score DESC;

945788-20160729181538059-1516798261.png

獲取某個學生成績排名並計算該學生和上一名學生成績差,是並列排名

SELECT *,
(SELECT count(DISTINCT score) FROM table_score AS b WHERE a.score<b.score)+1 AS rank, #獲取排名,並列
(SELECT b.score FROM table_score AS b WHERE b.score>a.score ORDER BY b.score LIMIT 1)-a.score AS subtract #獲取和上一名學生成績的差 
FROM table_score AS a WHERE a.s_id = 13; #獲取學生週三的成績排名和與上一名的成績差

945788-20160729181752919-1952308523.png

獲取全部學生成績排名-並列排名

SELECT *,
(SELECT count(DISTINCT score) FROM table_score AS b WHERE a.score<b.score)+1 AS rank #獲取排名-並列
FROM table_score AS a ORDER BY rank; #獲取學生成績排名

945788-20160729182353356-1008764020.png

獲取全部學生成績排名,不是並列排名。計算行號進行排名

SELECT a.*,
(@rowNum:=@rowNum+1) AS rank #計算行號
FROM table_score AS a,
(SELECT (@rowNum :=0) ) b
ORDER BY a.score DESC;

945788-20160729183045013-563930309.png

相關文章
相關標籤/搜索