题解 | #最差是第几名(二)#
最差是第几名(二)
http://www.nowcoder.com/practice/165d88474d434597bcd2af8bf72b24f1
sql求中位数
窗口函数法:(简单又巧妙)
正序:1 2 3 4 5
倒序:5 4 3 2 1===================》中位数3
正序:1 2 3 4 5 6
逆序:6 5 4 3 2 1=================》中位数3 4
结论;where a=b or abs(b-a)=1
#要么相等要么相差1
1、如果是序列数字,则需要用窗口函数row_number()对每个数字标号,over(order by ** asc)as a
over(order by ** desc)as b
2、如果需要对序列和求中位数,则有一个思想就是:求出正序和a和逆序和b,全部数字total。
key:判断条件:where a>=total/2 and b>=total/2
本题答案:
select t.grade
from
(
select
grade,
sum(number) over() as total,
sum(number) over(order by grade asc)as asc_grade,
sum(number) over(order by grade desc)as desc_grade
from class_grade
)as t
where t.asc_grade>=t.total/2 and t.desc_grade>=t.total/2
order by t.grade;