MySQL日记2: 成绩的排名
成绩表
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| score | decimal |
+-------------+---------+
Id是该表的主键。
该表的每一行都包含了一场比赛的分数。Score是一个有两位小数点的浮点值。
要点:
1. 分数应按从高到低排列。
2. 如果两个分数相等,那么两个分数的排名应该相同。
关键点在于:
找到每个成绩对应的排名,可以用到SELECT子查询
难点:
相同成绩的RANK是相同的,定义RANK要count(distinct )
思路是:
每当遇到一个score,就看有几个是大于等于它的,然后去重
SELECT
s1.score AS 'score', (SELECT COUNT(DISTINCT s2.score) FROM Scores s2 WHERE s1.score <= s2.scor ) AS 'rank'
FROM
Scores s1
ORDER BY
s1.score DESC
;
格式美化一下:
# 用到了SELECT中的子查询
# rank是关键字,不能直接写,要加引号
SELECT
s1.score AS 'score', (
SELECT
COUNT(DISTINCT s2.score)
FROM
Scores s2
WHERE
s1.score <= s2.score
) AS 'rank'
FROM
Scores s1
ORDER BY
s1.score DESC
;