LeetCode MySQL题目178. 分数排名

原题地址

/*
按S1表的Id分组,然后计算S2的Score比S1的组的Score大的元组的个数。
*/
SELECT S1.Score AS Score,  COUNT(DISTINCT S2.Score) AS Rank 
FROM Scores S1, Scores S2
WHERE S2.Score >= S1.Score
GROUP BY S1.Id
ORDER BY Rank;

比较容易理解的解法

SELECT S1.Score AS Score,  
(SELECT COUNT(DISTINCT S2.Score) FROM Scores S2 WHERE S2.Score >= S1.Score) AS Rank
FROM Scores S1 ORDER BY S1.Score DESC;

你可能感兴趣的:(数据库原理,#MySQL)