题解 | #考试分数(五)#

考试分数(五)

https://www.nowcoder.com/practice/b626ff9e2ad04789954c2132c74c0513

-- where tt.t_rank BETWEEN tt.total/2 and tt.total/2+1  ,表名tt.可指定也可以不指定;
-- job分组的分数排行: ROW_NUMBER() over(partition by job order by score desc) as t_rank 
-- 计算job分组下的score个数 count(score) over(PARTITION by job) total
-- 只要排行数t_rank 在total中位数要么t/2,要么t/2+1之间, 加上floor(t/2) 就不对,不用向下取整
select id,job ,score ,t_rank
from 
(select id,job,score,ROW_NUMBER() over(partition by job order by score desc) as t_rank ,count(score) over(PARTITION by job) as total from grade ) tt 
where tt.t_rank BETWEEN tt.total/2 and tt.total/2+1  order by id ;


-- 解法2,先算出中位数所在的位置start-end
select job ,
round((case when total%2=0 then total/2 else (total+1)/2 end ),0 ) as `start` ,
round (( case when total%2=0 then  total/2+1 else (total+1)/2 end),0) as `END`
from (Select job,count(*) as total from grade group by job ) a 
-- 嵌套得到t_rank=b.`start` or t_rank =b.`END` 
select tt.id,tt.job,tt.score,tt.t_rank from (select id,job ,score ,ROW_NUMBER() over(partition by job order by score desc)as t_rank from grade )tt left join 
(select job ,
round((case when total%2=0 then total/2 else (total+1)/2 end ),0 ) as `start` ,
round (( case when total%2=0 then  total/2+1 else (total+1)/2 end),0) as `END`
from (Select job,count(*) as total from grade group by job ) a ) b on tt.job=b.job where t_rank=b.`start` or t_rank =b.`END` order by id;









全部评论

相关推荐

04-28 11:34
西北大学 运营
牛客4396号:不好意思,这个照片猛一看像丁真
点赞 评论 收藏
分享
自由水:笑死了,敢这么面试不敢让别人说
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务