Leetcode 178. Rank Scores

原创 2016年08月31日 05:20:46

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

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode 262. Trips and Users

select allo.r, round(ifnull(canceled.c/allo.c,0),2) from (select count(1) as c,Request_at as r from ...

pthread_create()创建线程时传入多个参数

由于接口只定义了一个入参void *arg int pthread_create(pthread_t *tidp,const pthread_attr_t *attr, (void*)(*start_...

Database LeetCode Rank Scores

题目: Write a SQL query to rank scores. If there is a tie between two scores, both should have the sa...

[LeetCode]Rank Scores,解题报告

题目Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ...

Flat - Music scores and guitar tabs editor(乐谱编辑器)

听音乐是一种放松心情、舒缓压力的好方法,那么你有没有想过创造一首属于自己的音乐呢?Flat - Music scores and guitar tabs editor(乐谱编辑器)是一个简单小巧、灵活...

Project Euler:Problem 22 Names scores

Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-t...
  • youb11
  • youb11
  • 2015年06月01日 21:01
  • 531

hihoCoder 1236 Scores 解题报告(bitset + 分段暴力)

#1236 : Scores 时间限制:4000ms 单点时限:4000ms 内存限制:256MB 描述 Kyle is a student of Pro...
  • kbdwo
  • kbdwo
  • 2015年09月23日 18:36
  • 544

Codeforces 712D Memory and Scores【dp+前缀和】

D. Memory and Scores time limit per test 2 seconds memory limit per test 512 megabytes in...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Leetcode 178. Rank Scores
举报原因:
原因补充:

(最多只允许输入30个字)