给定天数的累积月份

时间:2016-05-22 18:11:20

标签: sql sql-server tsql sql-server-2012

我的表格如下

T1 (date int, dateYearMonth int, userID int, shopID int, amount numeric(18,2))

示例数据:

(20151212, 201512, 1, 1, 50.00),
(20151213, 201512, 1, 1, 30.00),
(20160110, 201601, 1, 1, 13.00)

我想为用户返回每个月的累计金额, 我的疑问是:

select t.dateYearMonth, t.userID,
sum(t.sum_amount) over
(partition by t.userID order by t.dateYearMonth
 rows between unbounded preceding and current row)
from (select dateYearMonth, userID, sum(amount) as sum_amount FROM T1
group by dateYearMonth, userID) t

有更优化的方法吗? 输出预期

(201512, 1, 1, 80.00), (201601, 1, 1, 93.00)

2 个答案:

答案 0 :(得分:0)

您可以使用:

SELECT DISTINCT dateYearMonth, userID
       ,total = SUM(amount) OVER(PARTITION BY userID ORDER BY dateYearMonth)
FROM T1;

LiveDemo

答案 1 :(得分:0)

我认为您的查询非常好。我认为它不会变得更好。

确保您有覆盖索引,如下所示:

CREATE NONCLUSTERED INDEX [IX] ON T1
(
    userID ASC
    ,dateYearMonth ASC
) INCLUDE(amount);

使用此索引,带有示例数据的临时表的执行计划如下所示:

execution plan

它只读取表中的所有行(索引),并对它们进行分组/求和,无需额外排序。