需求:
多条记录中按姓名分组,分组后的结果取中位数,若同一组记录行数为基数,打印正中间记录;若同一组记录行数为偶数,打印中间两条记录
结果
查询sql:
with Graduates as --创建虚表并添加记录,表名为:Graduates
(
select '2022-01' as period,'迈克' as name ,40 as income
union select '2022-02' as period,'迈克' as name ,30 as income
union select '2022-01' as period,'阿诺德' as name ,20 as income
union select '2022-02' as period,'阿诺德' as name ,25 as income
union select '2022-02' as period,'阿诺德' as name ,35 as income
union select '2022-01' as period,'劳伦斯' as name ,10 as income
union select '2022-02' as period,'劳伦斯' as name ,18 as income
union select '2022-03' as period,'劳伦斯' as name ,5 as income
union select '2022-04' as period,'劳伦斯' as name ,3 as income
)
select t.name,percentile_disc(0.5) within group (order by income) as rn from Graduates t
group by t.name
union
select t.name,percentile_disc(0.51) within group (order by income) as rn from Graduates t
group by t.name
;
补充:
1.percentile_disc(0.5) within group (order by income) 表示取中位数
2.percentile_disc函数,表示最接近请求百分位的离散值,传参0.5即50%,如果有偶数行,0.5默认把小的中位数取出来,传参0.51把偶数行较大的中位数取出来,并集结果输出。