LeetCode - mysql【178. 分数排名】

题178. 分数排名

LeetCode - mysql【178. 分数排名】_第1张图片

思路:查找比每个得分大于等于的个数,就是得分的排名。

SELECT s1.Score,COUNT(DISTINCT s2.Score) AS Rank1
FROM Scores AS s1,Scores AS s2 
WHERE s1.score<= s2.score

输出结果:

这是因为:Count( )计数方法,只返回每条数据的计算个数。

我们需要取出每条数据,分布进行个数计算。修改代码如下:

SELECT s1.Score,
(SELECT COUNT(DISTINCT s2.Score) FROM Scores AS s2 WHERE s1.score<= s2.score) AS Rank2
FROM Scores AS s1 ;

LeetCode - mysql【178. 分数排名】_第2张图片

标准答案为:

SELECT s1.Score,
(SELECT COUNT(DISTINCT s2.Score) FROM Scores AS s2 WHERE s1.score<= s2.score) AS Rank
FROM Scores AS s1 
ORDER BY s1.Score DESC;

 

你可能感兴趣的:(SQL)