SQL 76) 查询各个岗位分数的中位数位置上的所有grade信息

考试分数(五)

http://www.nowcoder.com/questionTerminal/b626ff9e2ad04789954c2132c74c0512

大牛解法)

  • 按id升序排序
select B.* 
from
(SELECT job,FLOOR((COUNT(*)+1)/2) AS `start`,FLOOR((COUNT(*)+1)/2)+if(COUNT(*) % 2=1,0,1) AS `end` 
FROM grade  GROUP BY job) A   -- 求出如上题的中位数区间
JOIN
(select g1.*, (
    select count(distinct g2.score) 
    from grade g2 
    where g2.score>=g1.score and g1.job=g2.job) as t_rank
from grade g1 ) B
on (A.job=B.job  and B.t_rank between A.start and A.end)  -- 成绩位于中位数区间
order by B.id

21/4/2
第二次修改,自己的做法,感觉更好理解

select a.id, b.job, a.score , a.t_rank
from 
(select job, floor((count(score)+1)/2) as 'start', floor((count(score)+2)/2) as 'end'
from grade
group by job)b
join
(select id, job, score, dense_rank()over(partition by job order by score desc) t_rank
from grade)a
on b.job = a.job
where a.t_rank between  b.start and b.end
order by a.id asc ;
SQL 文章被收录于专栏

SQL

全部评论
我也是方法二,但是不明白为啥t_rank的排序是desc
点赞 回复 分享
发布于 2021-12-01 00:47
a.t_rank between b.start and b.end 这个真是点睛之笔
点赞 回复 分享
发布于 2023-12-19 17:08 上海
第二种方法应该用row_number()吧
点赞 回复 分享
发布于 03-26 22:47 山东

相关推荐

11 收藏 评论
分享
牛客网
牛客企业服务