#中位数本身就是先按自然数排名,再取数。排序函数选用row_number
方法一(妙解)
用一条规则统一奇数个数时和偶数个数时的中位数位置。无论奇偶,中位数的位置距离(个数+1)/2 小于1,不信你随便写个试试。
select id,job,score,s_rank from (select * ,(row_number()over(partition by job order by score desc))as s_rank ,(count(score)over(partition by job))as num from grade)t1 where abs(t1.s_rank-(t1.num+1)/2)<1 order by id;
方法二(常规思路):
#对grade表添加组内排名列作为表1,各组中位数的表(也就是上题的查询)作为表2,
#用相同组(job)关联表1表2,用where筛出表1中的组内排名等于表2中组内start位置或end位置。
⚠️复制时把倒数第二行的&nbs***bsp;替换成为or,否则报错。【复制代码注意】
select t1.id ,t1.job ,t1.score ,t1.s_rank from (select id,job,score ,(row_number()over(partition by job order by score desc))as s_rank from grade)t1 join (select job ,case when count(score)%2=0 then ceiling(count(score)/2) else ceiling(count(score)/2) end as start1 ,case when count(score)%2=0 then ceiling(count(score)/2+1) else ceiling(count(score)/2) end as end1 from grade group by job)t2 on t1.job=t2.job where t1.s_rank=t2.start1&nbs***bsp;t1.s_rank=t2.end1 order by t1.id;