题解 | #获取员工其当前的薪水比其manager当前薪水还高的相关信息#
考试分数(四)
http://www.nowcoder.com/practice/502fb6e2b1ad4e56aa2e0dd90c6edf3c
和前面几个题差不多的思路,原本一直在纠结怎么样把中位数算出来,后面发现只要找出中位数位置就可以了,难度下降了很多(有递进到中位数思路的大佬们可以分享一下)。
第一步:造表
先将不同岗位的排名算出来,用到的函数有:dense_rank() over()
因为是按照 【岗位】分组,所以为partition by job 因为是按照 【分数】 排序,所以为order by score
表内函数为 select job,dense_rank() over(partition by job order by score) as rk from grade
第二步:求中位数范围→判断人数奇偶
1.因为是造了排名表,直接用最大的排名代替这个岗位的总人数→max(rk)
2.多条件判断 用到的函数:case when then else end
定义列:start
判断为奇数还是偶数 max(rk)%2=1 为奇数的中位数(max(rk)+1)/2 (可列数推导公式) 为偶数的中位数max(rk)/2
定义列:end
判断为奇数还是偶数 max(rk)%2=1 为奇数的中位数(max(rk)+1)/2 (可列数推导公式) 为偶数的中位数max(rk)/2+1
→→→别忘了保留0位小数
round((case when max(rk)%2=1 then (max(rk)+1)/2 else max(rk)/2 end),0) as start round((case when max(rk)%2=1 then (max(rk)+1)/2 else max(rk)/2+1 end ),0) as end
第三步:结合
select job , round((case when max(rk)%2=1 then (max(rk)+1)/2 else max(rk)/2 end),0) as start , round((case when max(rk)%2=1 then (max(rk)+1)/2 else max(rk)/2+1 end ),0) as end
from
(
select job,dense_rank() over(partition by job order by score) as rk
from grade
)t
group by job order by job