【发布时间】:2020-10-16 16:07:16
【问题描述】:
编写一个查询,找出每月至少需要多少销售额才能达到超过 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) 月份,需要 3 次销售(37、63、22 - 或 - 37+63+27)才能达到超过 100 次的销售额。
这是我尝试过的:
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;
但这不正确,我不知道从哪里开始。
【问题讨论】:
-
欢迎来到 SO。请只标记相关的关系型数据库
-
@Strawberry:给定聚合函数的
filter子句,这必须是 Postgres。 -
请确定您的主键
标签: sql postgresql sum window-functions