表:Students
Column Name | Type |
---|---|
student_id | int |
department_id | int |
mark | int |
student_id 包含唯一值。
该表的每一行都表示一个学生的 ID,该学生就读的院系 ID,以及他们的考试分数。
编写一个解决方案,以百分比的形式报告每个学生在其部门的排名,其中排名的百分比使用以下公式计算:
(student_rank_in_the_department - 1) * 100 / (the_number_of_students_in_the_department - 1)。
percentage 应该 四舍五入到小数点后两位。
student_rank_in_the_department 由 mark 的降序决定,mark 最高的学生是 rank 1。
如果两个学生得到相同的分数,他们也会得到相同的排名。
以 任意顺序 返回结果表。
结果格式如下所示。
示例 1:
输入:
Students 表:
student_id | department_id | mark |
---|---|---|
2 | 2 | 650 |
8 | 2 | 650 |
7 | 1 | 920 |
1 | 1 | 610 |
3 | 1 | 530 |
输出:
student_id | department_id | percentage |
---|---|---|
7 | 1 | 0.0 |
1 | 1 | 50.0 |
3 | 1 | 100.0 |
2 | 2 | 0.0 |
8 | 2 | 0.0 |
解释:
对于院系 1:
对于院系 2:
WITH tmp AS (
SELECT student_id,
department_id,
RANK() over (partition by department_id order by mark desc) AS rn
FROM Students
)
SELECT one.student_id,
one.department_id,
ROUND(IFNULL((one.rn-1)*100/(two.num-1), 0), 2) AS percentage
FROM tmp AS one
LEFT JOIN (
SELECT department_id,
COUNT(*) AS num
FROM tmp
GROUP BY department_id
) AS two USING(department_id)
SELECT student_id,
department_id,
ROUND(
IFNULL(
(rank() over (partition by department_id order by mark desc) - 1) * 100
/
(count(*) over (partition by department_id) - 1),
0
),
2
) AS percentage
FROM Students
SELECT student_id,
department_id,
ROUND(PERCENT_RANK() over (partition by department_id order by mark desc)*100, 2) AS percentage
FROM Students
PERCENT_RANK 窗口函数用于将每行按照 (rank - 1) / (rows - 1) 进行计算。
PERCENT_RANK 函数返回介于 0 和 1 之间的小数值