题解 | #最差是第几名(二)#
https://www.nowcoder.com/practice/165d88474d434597bcd2af8bf72b24f1
看了那么多大神解法,对于我这种算法弱智来说真跟不上,分享一个最傻瓜式,最易懂的方法吧。
题目要求找出中位数:总数基数输出1个,总数偶数输出2个
思路:延用上一题的题解,找到每个grade的最后一名的排名,观察这个最差排名是否包含中位数,包含则输出。
步骤:
1.查询每个grade的最差排名(同上一题)
with t0 as( select grade, number, sum(number)over(order by grade)num from class_grade )
2.将总数分奇偶数进行判断:当总数是奇数时,利用limit=1,取出1个grade;
b as( select grade,num from t0 where t0.num >= (select sum(number) from class_grade)/2 order by num limit 1 )
当总数是偶数时,再分情况判断:如果grade的最差排名数 >= 总数/2 + 1,则只输出1个grade;grade的最差排名数 >= 总数/2 输出2个grade
a as( select grade,num from t0 where t0.num >= (select sum(number) from class_grade)/2 order by num limit 2 ), , c as( select grade,num from t0 where t0.num >= (select sum(number) from class_grade)/2+1 order by num limit 1 )
3.最后取出中位数grade,将以上a,b,c三个表左连接,通过ifnull函数剔除联表查询中的空值
select ifnull(case when (select sum(number) from class_grade)%2=0 //取模判断奇偶 then (case when a.num >=(select sum(number) from class_grade)/2+1 //判断总数为偶数时两个中位数是否均在同一个grade中 then c.grade//是的话取其中1个 else a.grade end)//不是的话取2个 else b.grade end, '') from a left join b on a.grade = b.grade left join c on a.grade = c.grade