[LeetCode]Rank Scores

Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks.

+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+
For example, given the above Scores table, your query should generate the following report (order by highest score):

+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

这道题目让我们对分数进行排序。如果两个分数之间相同则存在相同的排名,需要注意的是,如果有相同排名后,下一个排名数字应该是一个连续的整数值:

在这里我们先拓展一下,先使用Excel函数来对此项题目求解:

在Excel中,可以使用SUMPRODUCT()函数来求解:

 接着我们使用SQL语句来实现该需求:

解法一:

SELECT Score, (SELECT COUNT(DISTINCT Score) FROM Scores WHERE Score >= s.Score)  Rank FROM Scores s ORDER BY Score DESC;

 此题的解法是把成绩按照倒序排序,再把去重后每一门成绩做比较大小来统计数;

咱们再做一次扩展:就是成绩依然排名,不过要求是当要重复排名的时候,之后的排名数会跳过重复数的排名

我们知道在Excel中使用Rank函数就可以实现:

那么在SQL中怎么实现这个排名呢:

猜你喜欢

转载自www.cnblogs.com/lsyb-python/p/11045200.html