【问题标题】:Percentile calculation with a window function带窗函数的百分位数计算
【发布时间】:2016-09-25 04:20:02
【问题描述】:

我知道您可以使用窗口函数获得数据子集的平均值、总计、最小值和最大值。但是是否有可能通过窗口函数获得中位数或第 25 个百分位数而不是平均值?

换句话说,我如何重写它以获得每个区域内的 id 和第 25 或第 50 个百分位数的销售数字,而不是平均值?

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

【问题讨论】:

    标签: postgresql aggregate-functions postgresql-9.5


    【解决方案1】:

    您可以使用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
    

    【讨论】:

    • 当我这样做时,我得到以下错误: OVER is not supported for ordered-set aggregate percentile_cont ...这很奇怪,因为我有 Postgres 9.5,我认为它在 9.4 中得到支持?
    • @StephenSmith。 . .文档——如果你仔细阅读的话——很清楚百分位函数只是聚合函数而不是窗口函数。
    猜你喜欢
    • 2021-03-21
    • 2011-12-29
    • 2013-06-20
    • 2021-02-26
    • 2016-07-28
    • 2017-08-29
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多