使用 SQL 计算百分位数 group/partition
Calculate percentiles using SQL for a group/partition
我想计算 SQL 中给定 partition/group 的百分位数。例如输入数据看起来像 -
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 实现此目的?
您可以使用 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;
我想计算 SQL 中给定 partition/group 的百分位数。例如输入数据看起来像 -
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 实现此目的?
您可以使用 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;