码疯窝

LeetCode 每日一题 — Rank Scores

2015/01/13 11:14:46    分类: 日志连载    0人评论 次浏览

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

分析: 思路是这样的, 先DISTINCT 或者 GROUP BY 然后对应的ROWNUM 就是他的RANK了. 然后再JOIN 原表就可以得出来RANK跟Score的关系了. 不过MYSQL 实现ROWNUM的方式一般用变量.

PS: 今天一口气做完了Leetcode更新的4道MYSQL 题目, 就不再做算法题了.

SELECT e.Score, t.Rank FROM Scores e
INNER JOIN (
	SELECT @rank := @rank + 1 AS Rank, Score
	FROM (
		SELECT Score FROM (select @rank := 0) r, Scores GROUP BY Score ORDER BY Score DESC
	) t
) t
ON e.Score = t.Score
ORDER BY e.Score DESC;
继续查看有关 日志连载的文章

0个访客评论