题目描述
编写一个 SQL 查询来实现分数排名。
如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。
题目链接: link.
解答
select
a.Score as Score,
(select count(distinct Score) from Scores b where b.Score >= a.Score) as 'Rank'
from Scores a
order by a.Score desc
需注意的点
RANK is a reserved word starting with MYSQL 8.0.2。如果Rank不加引号,则会出现如下报错
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Rank
from Scores a
order by a.Score desc' at line 4