首页 > 解决方案 > 一个账户前 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

但是上面的命令给出了一个语法错误

标签: sqlamazon-redshiftwindow-functions

解决方案


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
                         )

推荐阅读