sql - 您如何计算每月达到 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;
但这不正确,我不知道从哪里开始这个问题。
解决方案
您可以使用窗口函数。这个想法是枚举每个月的行,从最大的开始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
年份 | 月 | min_num_of_sales :--- | ----: | ---------------: 2019 | 1 | 3 2019 | 2 | 2 2019 | 3 | 2
推荐阅读
- glsl - Vulkan Uniform 中的数组问题
- kubernetes - 获取有关 AKS 中的污点控制器事件的通知
- 3d - Yaw-Roll-Pitch 变换
- sql - 如何在 SQL 中返回分多天的事件持续时间?
- pytorch - 在 Pytorch 中构建和训练自动编码器以降低向量输入的维度
- c# - 尝试安装 Emgu.CV.runtime.windows VS 2019 winforms,框架 4.8 时出现 EMGU 错误
- elasticsearch - 如何执行此弹性搜索查询
- jenkins - 在成功完成另外 5 个工作后触发构建管道工作
- ansible - Ansible import_task 并使用串行语法执行任务主机一一
- c++ - Clang-format:在函数尝试块中尝试之前如何避免换行?