我正在做这个问题,
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 |
+-------+------+
答案是:
Write your MySQL query statement below
SELECT Score,
CASE
WHEN @prev = Score THEN @rank
WHEN @prev := Score THEN @rank := @rank + 1
WHEN @rank := @rank + 1 THEN @rank
END AS Rank
FROM Scores, (SELECT @rank := 0, @prev := NULL) r
ORDER BY Score DESC
我不明白这部分:
WHEN @rank := @rank + 1 THEN @rank
当这条线可以被触发时,为什么我需要呢?
最佳答案
这一行:
WHEN @rank := @rank + 1 THEN @rank
它正在递增@rank
并返回递增的变量。它几乎完全等同于:
ELSE @rank := @rank + 1
(唯一的区别是 NULL
值,但可能该值不是 NULL
。)
这是什么逻辑?当表达式非零且非 NULL 时,MySQL 将其解释为 true。递增的正计数器将非零且非 NULL,因此 when
子句为 true。然后返回该值。
关于mysql - 选择时带有大小写的sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27913897/