Ste*_*ith 1 postgresql aggregate-functions postgresql-9.5
我知道你可以使用窗口函数获得一部分数据的平均值,总数,最小值和最大值.但是,有可能得到中位数,或第25百分位而不是窗函数的平均值?
换句话说,我如何重写这个以获得每个区域内的ID和第25或第50百分位销售数字而不是平均值?
SELECT id, avg(sales)
OVER (PARTITION BY district) AS district_average
FROM t
Run Code Online (Sandbox Code Playgroud)
您可以使用percentile_cont()
或将其写为聚合函数percentile_disc()
:
select district, percentile_cont(0.25) within group (order by sales)
from t
group by district;
Run Code Online (Sandbox Code Playgroud)
不幸的是,Postgres目前不支持这些作为窗口函数:
select id, percentile_cont(0.25) within group (order by sales) over (partition by district)
from t;
Run Code Online (Sandbox Code Playgroud)
所以,你可以使用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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3573 次 |
最近记录: |