178. Rank Scores

Rank Scores(LeetCode)

分數排名

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.

寫一個給分數排序的SQL查詢語句,如果有兩個相同的分數,那麼他們的排名是一樣的。另外,比上一個分數小的排名應該是下一個連續的整數值,排名應該沒有“漏洞”。

+----+-------+
| 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,你的查詢結果應該如下(從高分往下排序):

+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

Solution:

我參考的是StefanPochman的解析一,我比較喜歡這一個解決方法,因爲只涉及到一次查詢,效率肯定比多次查詢要好

SELECT
  Score,
  CAST(@rank := @rank + (@prev <> (@prev := Score)) as signed) Rank
FROM
  Scores,
  (SELECT @rank := 0, @prev := -1) init
ORDER BY Score desc

解釋如下:

(SELECT @rank := 0, @prev := -1) init :初始化變量 rank 和 prev,rank記錄當前排序,prev記錄前一個記錄的分數

CAST(@rank := @rank + (@prev <> (@prev := Score)) as signed) Rank:

CAST(value as type),將value轉換爲type類型,這裏因爲rank在做完運算後是一個浮點類型,需要轉成整形

@prev <> (@prev := Score):前一個分數和當前分數不相等,爲真,返回1,rank+1,排名靠後,若相等,爲假,返回0,排名不變,然後prev變量賦值爲新值(因爲這裏已經ORDER BY Score desc,所以不用擔心出現混亂的情況)

下面是StefanPochman的LeetCode的主頁和該參考答案鏈接,不過他最近不是很活躍。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章