【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

猜你喜欢

转载自blog.csdn.net/sphinx1122/article/details/83688049