[LeetCode] 178.Rank Scores 分数排行

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

这道题给了我们一个分数表,让我们给分数排序,要求是相同的分数在相同的名次,下一个分数在相连的下一个名次,中间不能有空缺数字,这道题我是完全照着史蒂芬大神的帖子来写的,膜拜大神中...大神总结了四种方法,那么我们一个一个的来膜拜学习,首先看第一种解法,解题的思路是对于每一个分数,找出表中有多少个大于或等于该分数的不同的分数,然后按降序排列即可,参见代码如下:

解法一:

SELECT Score, (SELECT COUNT(DISTINCT Score) FROM Scores WHERE Score >= s.Score) Rank FROM Scores s ORDER BY Score DESC;

解法二:

SELECT Score,(SELECT COUNT(*) FROM (SELECT DISTINCT Score s FROM Scores) t WHERE s >= Score) RankFROM Scores ORDER BY Score DESC;

解法三:

SELECT s.Score, COUNT(DISTINCT t.Score) RankFROM Scores s JOIN Scores t ON s.Score <= t.ScoreGROUP BY s.Id ORDER BY s.Score DESC;

解法四:

SELECT Score,@rank := @rank + (@pre <> (@pre := Score)) RankFROM Scores, (SELECT @rank := 0, @pre := -1) INIT ORDER BY Score DESC;

https://leetcode.com/discuss/40116/simple-short-fast

更多相关文章

  1. MySQL系列多表连接查询92及99语法示例详解教程
  2. Linux下MYSQL 5.7 找回root密码的问题(亲测可用)
  3. MySQL 什么时候使用INNER JOIN 或 LEFT JOIN
  4. Android(安卓)-- Android(安卓)JUint 与 Sqlite
  5. android中SqLite query中用selectionArgs处理字符传值
  6. android从服务器下载文件(php+apache+win7+MySql)
  7. Android(安卓)ORM SQL Top 5
  8. android SQLiteDatebase 实践
  9. Android(安卓)SQLiteDatabase的使用

随机推荐

  1. 2、创建android应用程序
  2. Ubuntu下连接Android设备
  3. android PhoneGap 的入门例子
  4. android 最全的shape属性
  5. Android(安卓)之 Context Menu 上下文菜
  6. 开发Android第四步,Android NDK 及 androi
  7. 向android studio导入android源生app
  8. View组件之各xml属性
  9. AndroidStudio 备忘录之Spinner(下拉列表)
  10. Android SDK 2.2 开发环境安装