我知道你可以使用窗口函数获得数据子集的平均值,总数,最小值和最大值。但是,有可能得到中位数,或第25个百分位而不是窗口函数的平均值吗?
换句话说,我如何重写这个以获得每个区域内的ID和第25或第50百分位销售数字而不是平均值?
SELECT id, avg(sales)
OVER (PARTITION BY district) AS district_average
FROM t
答案 0 :(得分:5)
您可以使用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