出每个人的排名
SELECT a1.Name, a1.Sales, COUNT(a2.Sales) Sales_Rank
FROM Total_Sales a1, Total_Sales a2
WHERE a1.Sales <= a2.Sales OR (a1.Sales=a2.Sales AND a1.Name = a2.Name)
GROUP BY a1.Name, a1.Sales
ORDER BY a1.Sales DESC, a1.Name DESC;
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
LeetCode上的计算排名:
https://leetcode.com/problems/rank-scores/description/
结果:
方案一:
SELECT
Score,
@rank := @rank + (@prev <> (@prev := Score)) Rank
FROM
Scores,
(SELECT @rank := 0, @prev := -1) init
ORDER BY Score desc
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
解析:方案一中,用了一种简化的判断方式,即 @prev <> (@prev := Score),
先将 变量 @prev 赋一个值 score,然后 将赋值前和赋值后进行比较,如果赋值前和赋值后相等,则返回0,@rank变量 +0,如果赋值前和赋值后不相等,那么返回1,@rank +1,即分数相同,那么排名也一样。
方案二:
SELECT
Score,
(SELECT count(distinct Score) FROM Scores WHERE Score >= s.Score) Rank
FROM Scores s
ORDER BY Score desc
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
方案三:
SELECT
Score,
(SELECT count(*) FROM (SELECT distinct Score s FROM Scores) tmp WHERE s >= Score) Rank
FROM Scores
ORDER BY Score desc
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
方案四:
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
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4