中位数(Median)又称中值,统计学中的专有名词,是按顺序排列的一组数据中居于中间位置的数,代表一个样本、种群或概率分布中的一个数值,其可将数值集合划分为相等的上下两部分。对于有限的数集,可以通过把所有观察值高低排序后找出正中间的一个作为中位数。如果观察值有偶数个,通常取最中间的两个数值的平均数作为中位数。
with temp as (
select 13 as num
union all
select 23 as num
union all
select 7 as num
union all
select 30 as num
union all
select 56 as num
union all
select 78 as num
union all
select 100 as num
union all
select 3 as num
)
方法1:使用hive自带函数
分析最中间的两个数为23和30,均值为26.5
select percentile(num, 0.5) from temp; ----26.5
方法2:正排倒排来一遍法
select avg(num)
from
(
select num
,row_number() over(order by num) as rn1
,row_number() over(order by num desc) as rn2
from temp
)as t
where rn1 = rn2 or abs(rn1-rn2) = 1
方法3:充分利用窗口函数
select avg(num)
from
(
select num
,row_number() over(order by num) as rn
,count(*) over() as n
from temp
)as t
where rn in (floor(n/2)+1,if(mod(n,2) = 0,floor(n/2),floor(n/2)+1))