Question

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

二刷:

  1. 这道题的核心在于自己创建新的变量。
  2. 这道题的还牵扯到SQL的优先级问题,我们单独拎出来@pre <> (@pre := Score)进行分析。
  3. 实际上这行的执行顺序是从左往右,并没有将括号内的优先拉出来运算。
    # Write your MySQL query statement below
    SELECT s.Score as Score,
    (@i:=@i+ (@pre <> (@pre := Score))) as Rank
    FROM Scores s, (select @i:=0, @pre:=-1) AS init
    ORDER BY s.Score DESC;
    

引用

  1. MySQL中变量的用法——LeetCode 178. Rank Scores