leetcode--Database--178. Score ranking

The topic is as follows

编写一个 SQL 查询来实现分数排名。

如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。

+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+
例如,根据上述给定的 Scores 表,你的查询应该返回(按分数从高到低排列):

+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+
重要提示:对于 MySQL 解决方案,如果要转义用作列名的保留字,可以在关键字之前和之后使用撇号。例如 `Rank`

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rank-scores
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Problem-solving ideas

Need obtained results are divided into two, first column Score, can be order bysorted to obtain the second number of columns may be obtained by (deduplication score) greater than a certain score.

first row

select s1.Score from Scores s1 order by s1.Score

the second list

The acquisition of this column is mainly to be able to understand, for example: there are several scores (100, 98, 98, 97...), to get a ranking of 97 points, as long as all the scores are de-weighted ( discinct score), and then the statistics are greater than or equal to 97 points are enough.

select count(distinct Score) from Score s2 where s2.Score>=x

x is the grade of each student in the first column above.

Combine the first column and the second column

select s1.Score,(select count(distinct Score) from Scores s2 where s2.Score>=s1.Score) AS 'Rank' from Scores s1 order by Score DESC

Guess you like

Origin blog.csdn.net/qq_41262903/article/details/106720669
Recommended