fantasia的博客

Somewhere on this planet

Leetcode 178. Rank Scores

178. Rank Scores

Total Accepted: 11758 Total Submissions: 48686 Difficulty: Medium

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    |
+-------+------+

思路:

这道题还是比较tricky的。一开始我想着用alter新建一个列,然后再排序,第一遍将小的score rank+1;第二遍将相同score的rank值变成一样。结果:

ALTER command denied to user 'student'@'localhost' for table 'Scores'

这题的解法是这样,

观察给定的例子,>=4的 rank是1;>=3.85的rank是2;>= 3.65 的rank是3,也就是说其rank为>=其score的distinct score数。

# Write your MySQL query statement below
select
  Score,
  (select count(distinct Score) from Scores where Score >= s.Score) as Rank
from Scores s
order by Score desc

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fantasiasango/article/details/52381243
文章标签: MySQL
个人分类: Database
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭