【问题标题】:Total revenue of an account for the preceding 12 months - Redshift SQL一个账户前 12 个月的总收入 - Redshift SQL
【发布时间】:2021-03-02 17:04:01
【问题描述】:

所以我的疑问在于 sql。我正在查找过去 12 个月的父帐户的总收入。 数据看起来像这样

revenue name month year
10000 abc 201001 2010-01-12
10000 abc 201402 2014-02-14
2000 abc 201404 2014-04-12
3000 abc 201406 2014-06-30
30000 def 201301 2013-01-14
6000 def 201304 2013-04-12
9000 def 201407 2013-07-19

输出应该是这样的

revenue name month year Running Sum
10000 abc 201001 2010-01-12 10000
10000 abc 201402 2014-02-14 10000
2000 abc 201404 2014-04-12 12000
3000 abc 201406 2014-06-30 15000
30000 def 201301 2013-01-14 30000
6000 def 201304 2013-04-12 36000
9000 def 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

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

【问题讨论】:

  • 很抱歉,我正在使用红移。我会更新的!
  • order by month range between current row and interval '12 months' 表示“从当前行(包括当前行)和所有下一行到一年后”。使用FROM PRECEDING INTERVAL 12 MONTH AND CURRENT ROW(或者可能是 11 个月?)...
  • 嗨,我仍然收到语法错误。可能 redshift 不支持间隔命令。我也在他们的文档中看到了这一点

标签: sql amazon-redshift window-functions


【解决方案1】:

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
                         )

【讨论】:

  • 您好,谢谢!解决方案看起来很棒。我只有一个问题,我遇到了一个语法错误,比如“窗口函数的 RANGE 子句尚未实现”,你知道吗?
  • 您好,月数不固定,也可能在一个月内有多个名字的收益。所以我不能对前面的数字 11 进行硬编码。
猜你喜欢
  • 2019-01-04
  • 2022-08-02
  • 2019-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-16
  • 2021-02-11
相关资源
最近更新 更多