SQL Server - TSQL:累计计数

时间:2013-11-21 01:58:47

标签: sql sql-server tsql

所以我有以下问题:

Select Year(DATEADD(MONTH,3,date)) as Year, Month(DATEADD(MONTH,3,date)) as Month, location, COUNT (agent_login_id)
from Agents
where Location = 'syd'
Group by Location, Year(DATEADD(MONTH,3,date)), Month(DATEADD(MONTH,3,date)) 

输出:

Year    Month   location    Count

2013    1   SYD 1
2013    3   SYD 11
2013    4   SYD 2
2013    5   SYD 2
2013    8   SYD 3
2013    9   SYD 1
2013    10  SYD 4
2013    11  SYD 7
2013    12  SYD 7
2014    1   SYD 3
2014    2   SYD 1

但我需要进行累积计数,例如这就是我需要它的样子

 Year   Month   location    Count Cumulative count
 2013   1   SYD 1           1
 2013   3   SYD 11          12
 2013   4   SYD 2           14

我该怎么做?

1 个答案:

答案 0 :(得分:1)

我将使用@t来表示您当前的查询

我称之为'完全积累'(基于原始问题)

-- 2012
;WITH t AS
(
    SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY l ORDER BY y, m)
    FROM @t
)
SELECT y, m, c, ISNULL(a + LAG(a,2) OVER(PARTITION BY l ORDER BY y, m), a) a
FROM (
    SELECT t1.y, t1.l, t1.m, t1.c, SUM(t2.c) a
    FROM t t1
    JOIN t t2 ON t2.rn <= t1.rn AND t2.l = t1.l
    GROUP BY t1.y, t1.l, t1.m, t1.c
) t

-- 2005+
;WITH t AS
(
    SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY l ORDER BY y, m)
    FROM @t
)
SELECT t1.y, t1.l, t1.m, t1.c, ISNULL(SUM(t2.c)+SUM(t3.c), MIN(t1.c)) a
FROM t t1
JOIN t t2 ON t2.rn <= t1.rn AND t2.l = t1.l
LEFT JOIN t t3 ON t3.rn < t2.rn-1
GROUP BY t1.y, t1.l, t1.m, t1.c

修改

正常运行总数(问题已得到纠正)

--2005+
;WITH t AS
(
    SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY l ORDER BY y, m)
    FROM @t
)
SELECT t1.y, t1.l, t1.m, t1.c, SUM(t2.c) a
FROM t t1
JOIN t t2 ON t2.rn <= t1.rn AND t2.l = t1.l
GROUP BY t1.y, t1.l, t1.m, t1.c

注意:如果您在当前查询中计算了该月的第一天,而不是使用YEAR()MONTH()(如果需要,请将这些计算留到最后),那么您可以避免使用{{1可能会看到一些性能改进