1. 程式人生 > >【MYSQL】分數的排名

【MYSQL】分數的排名

有以下資料

+----+-------+
| id | score |
+----+-------+
|  1 | 3.8   |
|  2 | 3.85  |
|  3 | 4.50  |
|  4 | 3.85  |
|  5 | 4.50  |
|  6 | 2.65  |
+----+-------+

把表格 tb_score的分數按從大到小排列,且把排名打印出來,相同的分數排名必須相同,結果如下

+-------+------+
| score | rank |
+-------+------+
| 4.50  |    1 |
| 4.50  |    1 |
| 3.85  |    2 |
| 3.85  |    2 |
| 3.8   |    3 |
| 2.65  |    4 |
+-------+------+


解答一:使用子查詢,在整個列表中找出有多少個大於或者等於此分數的不重複分數,倒序排列

SELECT score,
(select count(distinct score) from scores where score >=s.score)
Rank from scores s order by score DESC;

解答二,使用連表,當左表的分數小於等於右表的分數,對右表計數,按ID分組,按倒序排列

SELECT score,count(distinct s.score) as rank 
from scores a join scores s on a.score<=s.score 
group by a.id order by a.score desc