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.html
+----+-------+ | 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):post
+-------+------+ | Score | Rank | +-------+------+ | 4.00 | 1 | | 4.00 | 1 | | 3.85 | 2 | | 3.65 | 3 | | 3.65 | 3 | | 3.50 | 4 | +-------+------+
這道題給了咱們一個分數表,讓咱們給分數排序,要求是相同的分數在相同的名次,下一個分數在相連的下一個名次,中間不能有空缺數字,這道題我是徹底照着史蒂芬大神的帖子來寫的,膜拜大神中...大神總結了四種方法,那麼咱們一個一個的來膜拜學習,首先看第一種解法,解題的思路是對於每個分數,找出表中有多少個大於或等於該分數的不一樣的分數,而後按降序排列便可,參見代碼以下:學習
解法一:url
SELECT Score, (SELECT COUNT(DISTINCT Score) FROM Scores WHERE Score >= s.Score) Rank FROM Scores s ORDER BY Score DESC;
跟上面的解法思想相同,就是寫法上略有不一樣:spa
解法二:code
SELECT Score, (SELECT COUNT(*) FROM (SELECT DISTINCT Score s FROM Scores) t WHERE s >= Score) Rank FROM Scores ORDER BY Score DESC;
下面這種解法使用了內交,Join是Inner Join的簡寫形式,本身和本身內交,條件是右表的分數大於等於左表,而後羣組起來根據分數的降序排列,十分巧妙的解法:htm
解法三:blog
SELECT s.Score, COUNT(DISTINCT t.Score) Rank FROM Scores s JOIN Scores t ON s.Score <= t.Score GROUP BY s.Id ORDER BY s.Score DESC;
下面這種解法跟上面三種的畫風就不太同樣了,這裏用了兩個變量,變量使用時其前面須要加@,這裏的:= 是賦值的意思,若是前面有Set關鍵字,則能夠直接用=號來賦值,若是沒有,則必需要使用:=來賦值,兩個變量rank和pre,其中rank表示當前的排名,pre表示以前的分數,下面代碼中的<>表示不等於,若是左右兩邊不相等,則返回true或1,若相等,則返回false或0。初始化rank爲0,pre爲-1,而後按降序排列分數,對於分數4來講,pre賦爲4,和以前的pre值-1不一樣,因此rank要加1,那麼分數4的rank就爲1,下面一個分數仍是4,那麼pre賦值爲4和以前的4相同,因此rank要加0,因此這個分數4的rank也是1,以此類推就能夠計算出全部分數的rank了。排序
解法四:leetcode
SELECT Score, @rank := @rank + (@pre <> (@pre := Score)) Rank FROM Scores, (SELECT @rank := 0, @pre := -1) INIT ORDER BY Score DESC;
參考資料:
https://leetcode.com/discuss/40116/simple-short-fast