使用 SQL 计算组/分区的累积百分位数

时间:2021-07-14 03:13:45

标签: sql snowflake-schema

我想计算 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       2.5      5.25     7     

因此,基本上对于产品 ID 111,我只需要为产品 ID 111 取quantity_purchased 的百分位数,但随着我在该列中的进一步操作,百分位数应该是产品 ID 222 的累积含义百分位数将考虑产品 ID 111 和产品 ID 222 (2,3,2,5,2,6,7,2) 的 quantity_purchased 值进行计算。类似地,如果数据中有产品 ID 333,那么对于产品 ID 333,我将根据与产品 111、产品 222 和产品 333 关联的所有数量购买值计算百分位数,并将结果存储在产品 333 行中。如何使用 SQL 实现这一点?

2 个答案:

答案 0 :(得分:2)

很好奇,但我认为您需要扩展每个产品 ID 的数据:

select t.product_id, min(t2.quantity_purchased), max(t2.quantity_purchased),
       percentile_cont(0.25) within group (order by t2.quantity_purchased),
       percentile_cont(0.50) within group (order by t2.quantity_purchased),
       percentile_cont(0.75) within group (order by t2.quantity_purchased)
from t join
     t t2
     on t2.product_id <= t.product_id
group by t1.product_id;

答案 1 :(得分:0)

这使用了 PERCENTILE_CONT 而不是 PERCENTILE_DISC 返回的关键差异 val 是基于使用线性插值的连续分布,其中值不完美排列 - 根据您的用例,这可能会提供更准确数据点。 :-)

$adContent  = $getDataAd->Ad_Content;
// This REGEX its ok, replace all \r\n\r\n\r\n\r\n... for 2 <br> but broken if detect a space :(
$pattern    = "/(?:\r?\n[ ]*)+/"; 
$adContent  = preg_replace($pattern, "<br><br>", $adContent);

enter image description here

复制|粘贴|在雪花中运行

select
    ProductID,
    min(Quantity_Purchased::float) min,
    PERCENTILE_CONT(.25) WITHIN GROUP (ORDER BY Quantity_Purchased ) as "25%",
    PERCENTILE_CONT(.50) WITHIN GROUP (ORDER BY Quantity_Purchased ) as "50%",
    PERCENTILE_CONT(.75) WITHIN GROUP (ORDER BY Quantity_Purchased ) as "75%" ,
    max(Quantity_Purchased) max
from
    cte
group by
    1