postgreSQL分组查询中位数,偶数行输出中间两条记录

需求:

多条记录中按姓名分组,分组后的结果取中位数,若同一组记录行数为基数,打印正中间记录;若同一组记录行数为偶数,打印中间两条记录

结果
在这里插入图片描述

查询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把偶数行较大的中位数取出来,并集结果输出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值