我需要计算T-SQL中的累积计数。这可以这样做:
WITH DATASET AS (SELECT '2014-01-28' AS [DATE], 1 AS [COUNT]
UNION
SELECT '2014-01-29' AS [DATE], 5 AS [COUNT]
UNION
SELECT '2014-01-30' AS [DATE], 15 AS [COUNT]
UNION
SELECT '2014-01-31' AS [DATE], 4 AS [COUNT]
UNION
SELECT '2014-02-01' AS [DATE], 7 AS [COUNT]
UNION
SELECT '2014-02-02' AS [DATE], 1 AS [COUNT]
)
, CTE AS (SELECT *
,ROW_NUMBER() OVER (ORDER BY [DATE]) ROWNUM
FROM DATASET
)
SELECT CTE1.[DATE]
,CTE1.[COUNT]
,SUM(CTE2.[COUNT]) AS CUM_CNT
FROM CTE CTE1
JOIN CTE CTE2 ON CTE2.ROWNUM <= CTE1.ROWNUM
GROUP BY CTE1.[DATE]
,CTE1.[COUNT]
返回:
DATE COUNT CUM_CNT
2014-01-28 1 1
2014-01-29 5 6
2014-01-30 15 21
2014-01-31 4 25
2014-02-01 7 32
2014-02-02 1 33
但我想重置每个月的累积计数,因此返回的数据应为:
DATE COUNT CUM_CNT
2014-01-28 1 1
2014-01-29 5 6
2014-01-30 15 21
2014-01-31 4 25
2014-02-01 7 7
2014-02-02 1 8
是否可以在T-SQL中实现这一点?怎么样?
答案 0 :(得分:4)
从SQL Server 2012+开始,您可以使用SUM
的窗口版本来计算运行总计。您只需PARTITION
YEAR([DATE]), MONTH([DATE])
获得预期结果:
WITH DATASET AS (
SELECT '2014-01-28' AS [DATE], 1 AS [COUNT]
UNION
SELECT '2014-01-29' AS [DATE], 5 AS [COUNT]
UNION
SELECT '2014-01-30' AS [DATE], 15 AS [COUNT]
UNION
SELECT '2014-01-31' AS [DATE], 4 AS [COUNT]
UNION
SELECT '2014-02-01' AS [DATE], 7 AS [COUNT]
UNION
SELECT '2014-02-02' AS [DATE], 1 AS [COUNT]
)
SELECT [DATE], [COUNT],
SUM([COUNT]) OVER (PARTITION BY YEAR([DATE]), MONTH([DATE])
ORDER BY [DATE]) AS CUM_CNT
FROM DATASET