知识点
- 首先原表上加一列排名,因为要的是中位数只会有一个或者两个所以窗口函数排序使用row_number,题目要求是最大的是第一所以order by 使用降序排序。
- 再加上各岗位的中位数列,因为中位数有一个或两个所以需要两列。floor()向下取整,ceiling()向上取整
- 中位数就是排名在两个数直接的数
代码
select g1.id, g1.job, g1.score, g1.r as t_rank
from (
select *,
row_number() over(partition by job order by score desc) as r
from grade
) as g1
join (
select job,
floor((count(id)+1)/2) as a1,
ceiling((count(id)+1)/2) as a2
from grade
group by job
) as g2
on g1.job = g2.job
where g1.r between a1 and a2
order by g1.id