我知道你可以通过一个窗口函数得到数据子集的平均值、总值、最小值和最大值。但是,有没有可能,比如说,用窗口函数得到中位数,或者25%而不是平均值呢?
换言之,我该如何重写它来获得每个地区内的id和25%或50%的销售数字,而不是平均值?
SELECT id, avg(sales)
OVER (PARTITION BY district) AS district_average
FROM t
最佳答案
您可以使用percentile_cont()
或percentile_disc()
将其作为聚合函数编写:
select district, percentile_cont(0.25) within group (order by sales)
from t
group by district;
不幸的是,Postgres目前不支持这些窗口功能:
select id, percentile_cont(0.25) within group (order by sales) over (partition by district)
from t;
因此,您可以使用
join
:select t.*, p_25, p_75
from t join
(select district,
percentile_cont(0.25) within group (order by sales) as p_25,
percentile_cont(0.75) within group (order by sales) as p_75
from t
group by district
) td
on t.district = td.district
关于postgresql - 带窗函数的百分数计算,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39683330/