2016-09-25 44 views
0

我知道您可以使用窗口函數獲取數據子集上的平均值,總計,最小值和最大值。但是,有可能得到中位數或第25百分位數,而不是使用窗函數的平均數?使用窗口函數進行百分比計算

換句話說,我怎麼重寫這個獲得ID和每個分區而不是平均中的第25或第50百分位的銷售數字?

SELECT id, avg(sales) 
    OVER (PARTITION BY district) AS district_average 
FROM t 

回答

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 
+0

當我這樣做,我得到以下錯誤: OVER不支持有序集總PERCENTILE_CONT ...這是奇怪的,因爲我的Postgres 9.5,我想成爲支持9.4? –

+1

@StephenSmith。 。 。文檔 - 如果您仔細閱讀 - 明確指出百分位數函數只是聚合函數而不是窗口函數。 –