MySql 實現數據排名各版本總結


 

一、MySql 8.0 以下 實現排名


--
方法一
SELECT name, score, @rank := @rank + 1 as pm FROM scores A, (SELECT @rank := 0) B ORDER BY score DESC; -- 方法二 select C.* from ( SELECT A.*, @rank := @rank + 1 as pm FROM ( SELECT name, score FROM scores ORDER BY score DESC ) A, (SELECT @rank := 0) B ) as C; -- 方法三 select B.*, @curBank := IF(@prevRank = B.score, @curBank, @incRank) as 'pm', @incRank := @incRank + 1 as 'inc', @prevRank := B.score as 'sc' from ( select name, score from scores A, (select @curBank := 0, @prevRank := null, @incRank := 1) r group by name ) as B order by B.score desc; -- 方法四 select B.*, @curBank := IF(@prevRank = B.score, @curBank, @incRank) as 'pm', @incRank := @curBank + 1 as 'inc', @prevRank := B.score as 'sc' from ( select name, score from scores A, (select @curBank := 0, @prevRank := null, @incRank := 1) r group by name ) as B order by B.score desc;
        

 

結果一(方法一、方法二):

   

 

 

結果二(方法三):

   

 

結果三(方法四):

    

 

 

二、MySql 8.0 實現排名

 

函數 作用
RANK 並列跳躍排名,並列即相同的值,相同的值保留重復名次,遇到下一個不同值時,跳躍到總共的排名。
DENSE_RANK 並列連續排序,並列即相同的值,相同的值保留重復名次,遇到下一個不同值時,依然按照連續數字排名。
ROW_NUMBER 連續排名,即使相同的值,依舊按照連續數字進行排名。

  


--
方法一 select name,score, rank() over(ORDER BY score desc) as 'pm' from scores; -- 方法二 select name,score, dense_rank() over(ORDER BY score desc) as 'pm' from scores; -- 方法三 select name,score, row_number() over(ORDER BY score desc) as 'pm' from scores;

 

結果一:

   

 

  

結果二:

   

 

 

結果三:  

   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM