查询各个岗位分数的中位数位置上的所有grade信息,并且按id升序排序。
思路:
- 使用
row_number()和join找到按照成绩排序后,row_number = 中位数位置的分数; - 中位数位置结合floor()函数向下取整,ceiling()向上取整进行计算。
中位数位置:
eg1.每个岗位(job)对应的成绩总个数为4,那么中位数位置为2,3;
eg2.每个岗位(job)对应的成绩总个数为5,那么中位数位置为3;
每个岗位(job)对应的成绩总个数计算:count(id) group by job
因此得到中位数位置可表示为floor((count(id) + 1)/ 2), ceiling((count(id) + 1)/ 2)
select
id
,g.job as job
,score
,rk
from (--分数排名计算
select
id
,job
,score
,row_number() over(
partition by job
order by score desc
) as rk
from grade
) g
left join (--中位数位置计算
select
job
,floor((count(id) + 1)/ 2) as m1
,ceiling((count(id) + 1)/ 2) as m2
from grade
group by job
) m
on g.job = m.job
where rk between m1 and m2 -- 过滤,保证row_number处于中位数位置
order by id
; 
京公网安备 11010502036488号