首页 > 其他 > 详细

178.LeetCode Rank Scores

时间:2016-04-17 12:59:07      阅读:207      评论:0      收藏: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    |
+-------+------+
================================================================================
思路:先查出来score的排名在inner join Scores表。
SELECT
	s1.score,
	s2.rank
FROM
	Scores s1,
	(
		SELECT
			s.score,
			(
				SELECT
					count(1)
				FROM
					(
						SELECT DISTINCT
							score
						FROM
							Scores
					) t
				WHERE
					t.score >= s.score
			) rank
		FROM
			(
				SELECT DISTINCT
					score
				FROM
					Scores
			) s
	) s2
WHERE
	s1.score = s2.score
ORDER BY
	rank ASC

  





178.LeetCode Rank Scores

原文:http://www.cnblogs.com/Scort/p/5400612.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!