题目
编写 SQL 查询对分数进行排序。排名按以下规则计算:
1,分数应按从高到低排列;如果两个分数相等,那么两个分数的排名应该相同。
2,在排名相同的分数后,排名数应该是下一个连续的整数。换句话说,排名之间不应该有空缺的数字。
3,按 score 降序返回结果表。
分析
1,按题意,首先需要对分数进行排名。
由于要求分数相同排名相同,故可以先按分数进行分组,过滤掉重复项,再基于这个结果按分数降序进行排名。
1)按分数进行分组,过滤掉重复项
select
score
from
Scores
group by
Scores.score
order by
Scores.score desc
2)基于上述结果进行排名。其中,排名需要新增一个列,值为自增。
select
(@r:=@r+1) as temp, a.score
from
(
select
score
from
Scores
group by
Scores.score
order by
Scores.score desc
) a,
(
select @r:=0
) r
2,接着,使用原表与步骤1得到的分数排名表建立一个左连接(关联条件为分数相等),并对连接后的表格按分数进行降序排序,即可得到最终结果
select
Scores.score, b.rank
from
Scores
left join
(
select
CONVERT((@r:=@r+1), SIGNED) as 'rank', a.score
from
(
select score from Scores group by Scores.score order by Scores.score desc
) a,
(
select @r:=0
) r
) b
on
Scores.score = b.score
order by
Scores.score desc