每3天SQL累积总和()
我有这样的表
date amount
2020-02-01 5
2020-02-02 2
2020-02-03 10
2020-02-04 2
2020-02-06 3
2020-02-07 1
,我需要每3天每3天进行sum():
date amount sum
2020-02-01 5 5
2020-02-02 2 7
2020-02-03 10 17
2020-02-04 2 2
2020-02-06 3 5
2020-02-07 1 1
...
因此,当几天之间的差异为3时,总和应该重新开始。有些日子可能不在桌子上。
我尝试使用窗口函数进行此操作,例如sum(nument)(按日期订购)
,但我不知道如何设置固定的天数并获得这样的累积总和的日期差异。在任何SQL中都可以吗?
I have a table like this
date amount
2020-02-01 5
2020-02-02 2
2020-02-03 10
2020-02-04 2
2020-02-06 3
2020-02-07 1
And I need sum() every 3 days as below:
date amount sum
2020-02-01 5 5
2020-02-02 2 7
2020-02-03 10 17
2020-02-04 2 2
2020-02-06 3 5
2020-02-07 1 1
...
So when a difference between days is 3, the summation should start over. Some days may not be in the table.
I tried to do this with window function like sum(amount) over (order by date)
but I have no idea how to set a fixed number of days and get the date difference in cumulative sum like this. Is it possible in any SQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在MS SQL Server'2020-02-01
'中是您想要的开始日期。
In MS Sql Server
'2020-02-01' is a starting date you want.
,如果您可以访问SQL Server 2022(昨天进入预览),则可以进行一些乐趣。可以使用
date_bucket
将分区中的日期
到3天,以最低日期作为开始日期。结果图像如预期的,因为2022年的提琴是不存在的:

For a bit of fun, if you had access to SQL Server 2022 (which went into preview yesterday) you could use
DATE_BUCKET
to "round" the date in thePARTITION BY
to 3 days, using the minimum date as the starting date.Image of results as expected, as Fiddles of 2022 don't exist:
