计算占我销售额 50% 的产品数量

Calculate the number of products responsible for 50% of my sales

我有一家商店,在不同的国家/地区销售产品。

我最终得到了这样的销售额 table(还有更多的月份)

Month Country Product Sales
01-2022 UK Tomato 10
01-2022 UK Banana 4
01-2022 UK Garlic 1
01-2022 FR Tomato 1
01-2022 FR Banana 2
01-2022 FR Garlic 1

我想知道占每月销售额 50% 的产品数量和国家/地区。像这样。

Month Country Nb products accountable for 50% sales
01-2022 UK 1
02-2022 UK 3
03-2022 UK 2
01-2022 FR 1
02-2022 FR 4
03-2022 FR 3

objective 是让我的目录占大部分销售额的百分比。示例:我目录的 10% 代表销售额的 50%。

我试过用多个window函数解决问题,我已经搜索了开放主题没有成功

我终于找到了调整 windows 函数的解决方案。

,t1 AS (
SELECT 
*
,SUM(sales) OVER (PARTITION BY country_group, order_date ORDER BY sales DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) AS running_total 
,0.5*SUM(sales) OVER(PARTITION BY country_group, order_date) AS total_sales_x_50perc
FROM t0
ORDER BY 1
)


SELECT 
order_date
,country_group
,COUNT(DISTINCT CASE WHEN running_total <= total_sales_x_50perc THEN product ELSE NULL END) AS nb_products
,COUNT(DISTINCT product) AS total_nb_products
,COUNT(DISTINCT CASE WHEN running_total <= total_sales_x_50perc THEN product ELSE NULL END)/COUNT(DISTINCT products) AS perc
FROM t1
GROUP BY 1,2
ORDER BY 1