sql - 一个账户前 12 个月的总收入 - Redshift SQL
问题描述
所以我的疑问在于sql。我正在寻找过去 12 个月的父帐户的总收入。数据看起来像这样
收入 | 姓名 | 月 | 年 |
---|---|---|---|
10000 | 美国广播公司 | 201001 | 2010-01-12 |
10000 | 美国广播公司 | 201402 | 2014-02-14 |
2000 | 美国广播公司 | 201404 | 2014-04-12 |
3000 | 美国广播公司 | 201406 | 2014-06-30 |
30000 | 定义 | 201301 | 2013-01-14 |
6000 | 定义 | 201304 | 2013-04-12 |
9000 | 定义 | 201407 | 2013-07-19 |
输出应该是这样的
收入 | 姓名 | 月 | 年 | 运行总和 |
---|---|---|---|---|
10000 | 美国广播公司 | 201001 | 2010-01-12 | 10000 |
10000 | 美国广播公司 | 201402 | 2014-02-14 | 10000 |
2000 | 美国广播公司 | 201404 | 2014-04-12 | 12000 |
3000 | 美国广播公司 | 201406 | 2014-06-30 | 15000 |
30000 | 定义 | 201301 | 2013-01-14 | 30000 |
6000 | 定义 | 201304 | 2013-04-12 | 36000 |
9000 | 定义 | 201407 | 2013-07-19 | 45000 |
我尝试过使用类似这样的窗口功能以及我需要的逻辑
select revenue, name, date, month,
sum(revenue) over (partition by name order by month rows between '12 months' preceding AND CURRENT ROW )
from table
但是上面的命令给出了一个语法错误
解决方案
Redshift 不支持窗口框架规范中的间隔。
因此,转换为数字。在这种情况下,一个方便的方法是自某个时间点以来的月数:
select revenue, name, date, month,
sum(revenue) over (partition by name
order by datediff(month, '1900-01-01', month)
range between 12 preceding and current row
)
from table;
我会注意到您的逻辑将 13 个月的数据相加,而不是 12 个月。我怀疑您想要between 11 preceding and current row
.
rows between
如果您有所有月份的数据,则可以使用:
sum(revenue) over (partition by name
order by datediff(month, '1900-01-01', month)
rows between 12 preceding and current row
)
推荐阅读
- excel - 如何遍历过滤表并使用 vba 检查每一行是否在另一张表中?
- c# - 图像未显示在 ListView Xamarin 中
- ruby-on-rails - 如何在 capybara 测试中触发 keyup。我已经尝试了所有标准方法
- java - 使用属性文件创建 Java Spring Bean
- android - 无法将数据从 Activity 发送到 Fragment
- continuous-integration - Gitlab预定义变量未填充
- python-3.x - 在Page GUI python中单击按钮时如何获取文本框条目中的setText值?
- .net-core - 带有标签的.Net Core 2.1 asp-for不起作用
- sql - 在 Access 中制作表单,我想根据所选参数过滤输入
- android - 我可以将谷歌对讲的文本到语音输出捕获为文本吗?