首页 > 解决方案 > 您如何计算每月达到 100 次销售目标所需的最低销售额?

问题描述

编写一个查询,找出每月至少需要多少销售额才能达到超过 100 的累计销售额。

表代码:

DROP TABLE IF EXISTS q1sales;

CREATE TABLE q1sales (
year double precision,
month integer,
sales integer
);

INSERT INTO q1sales VALUES 
(2019, 1, 37),
(2019, 1, 63),
(2019, 1, 22),
(2019, 1, 27),
(2019, 2, 27),
(2019, 2, 40),
(2019, 2, 76),
(2019, 2, 24),
(2019, 3, 46),
(2019, 3, 74),
(2019, 3, 23),
(2019, 3, 95);

预期输出:

year month min_num_of_sales
2019     1                3
2019     2                2
2019     3                2

例如,在 1 月 (1) 月份,销售额达到 100 以上需要 3 个销售额(37、63、22 - 或 - 37+63+27)。

这是我尝试过的:

select year, month, (
select 
count(s) filter(where month = 1) and s in 
(select sum(s) as sums from sale2 where sums > 100)
from sale2
) 
from sale2;

但这不正确,我不知道从哪里开始这个问题。

标签: sqlpostgresqlsumwindow-functions

解决方案


您可以使用窗口函数。这个想法是枚举每个月的行,从最大的开始sale,并计算相应的运行总和。然后,您可以在达到阈值时过滤该行:

select year, month, rn min_num_of_sales
from (
    select s.*, 
        sum(sales) over(partition by year, month order by sales desc) running_sales,
        row_number() over(partition by year, month order by sales desc) rn
    from q1sales s
) t
where running_sales > 100 and running_sales - sales <= 100

DB Fiddle 上的演示

年份 | 月 | min_num_of_sales
:--- | ----: | ---------------:
2019 | 1 | 3
2019 | 2 | 2
2019 | 3 | 2

推荐阅读