【问题标题】:Calculate percentiles using SQL for a group/partition使用 SQL 计算组/分区的百分位数
【发布时间】:2021-09-22 22:45:35
【问题描述】:

我想计算 SQL 中给定分区/组的百分位数。例如输入数据看起来像 -

CustID     Product ID     quantity_purchased    
1          111                2
2          111                3
3          111                2 
4          111                5
1          222                2
2          222                6
4          222                7
6          222                2

我想获得每个产品 ID 组的百分位数。输出应该是 -

Product ID    min      25%      50%      75%     max
    111        2        2       2.5      3.5      5
    222        2        2        4       6.25     7

如何使用 SQL 实现这一点?

【问题讨论】:

    标签: sql snowflake-schema


    【解决方案1】:

    你可以使用percentile_cont():

    select product_id, min(quantity_purchased), max(quantity_purchased),
           percentile_cont(0.25) within group (order by quantity_purchased),
           percentile_cont(0.50) within group (order by quantity_purchased),
           percentile_cont(0.75) within group (order by quantity_purchased)
    from t
    group by product_id;
    

    【讨论】:

      猜你喜欢
      • 2021-09-23
      • 2012-10-28
      • 1970-01-01
      • 2021-02-26
      • 2020-10-07
      • 2021-11-29
      • 2011-12-29
      • 2013-06-20
      • 2017-09-04
      相关资源
      最近更新 更多