【问题标题】:How to run a 3 month sum of rows in SQL Server如何在 SQL Server 中运行 3 个月的总行数
【发布时间】:2018-06-18 20:57:17
【问题描述】:

我正在尝试在 SQL Server 2014 中复制此行为。我每月工作的总美元数,但我想要一个新列,将美元和当前和未来 2 个月相加,并将总数放入当前月份行。如何使用 SQL Server 完成此任务?

Date      Dollars   3 MONTH SUM
1/1/2018    10      37
2/1/2018    12      32
3/1/2018    15      36
4/1/2018    5       36
5/1/2018    16      34
6/1/2018    15      23
7/1/2018    3       27
8/1/2018    5       40
9/1/2018    19      46
10/1/2018   16      27
11/1/2018   11      11

我试过了:

SUM(dollars) OVER (ORDER BY date ROWS BETWEEN current row and 2 following) AS [3 month sum]

但计算不准确。这是正确的方法吗,我只是没有正确地做,还是有更好的方法?

【问题讨论】:

  • 你能提供你期望的结果吗?
  • 实际上,我刚刚弄清楚发生了什么。日期不全。几个月不见了。我的解决方案实际上效果很好。

标签: sql-server cumulative-sum


【解决方案1】:

这似乎可行,而且看起来很容易阅读

declare @Incomings table([Date] Datetime, Dollars int)
insert into @Incomings
values
('20180101', 10)
,('20180201', 12)
,('20180301', 15)
,('20180401', 5)
,('20180501', 16)
,('20180601', 15)
,('20180701', 3)
,('20180801', 5)
,('20180901', 19)
,('20181001', 16)
,('20181101', 11)


select * , (select SUM(Dollars) from @Incomings where [Date] between i.[Date] and DATEADD(MONTH,2,i.[Date]))
from @Incomings i

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 2013-02-03
    相关资源
    最近更新 更多