关闭

Leetcode 178. Rank Scores

标签: MySQL
288人阅读 评论(0) 收藏 举报
分类:

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

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:37312次
    • 积分:1663
    • 等级:
    • 排名:千里之外
    • 原创:133篇
    • 转载:3篇
    • 译文:0篇
    • 评论:24条
    文章分类
    最新评论