SQL累积计数

时间:2013-10-14 13:26:46

标签: sql sql-server sql-server-2008

我有部门的表。我需要计算在哪个部门内有多少人。

很容易做到这一点
SELECT DEPT,
       COUNT(*) as 'Total'
    FROM SR
    GROUP BY DEPT;

现在我还要做累积计数如下:

enter image description here

我找到了一些计算运行总数的SQL,但不是这样的情况。在这种情况下,你能给我一些建议吗?

2 个答案:

答案 0 :(得分:8)

这是使用CTE代替光标的方法:

WITH Base AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY [Count] DESC) RowNum,
    [Dept],
    [Count]
    FROM SR
)
SELECT SR.Dept, SR.Count, SUM(SR2.[Count]) Total
FROM Base SR
INNER JOIN Base SR2
    ON SR2.RowNum <= SR.RowNum
GROUP BY SR.Dept, SR.Count
ORDER BY SR.[Count] DESC

请注意,这是按照示例结果降序Count进行排序。如果还有一些未显示的列应该用于排序,则只需替换每个Count子句中的ORDER BY

SQL Fiddle Demo

答案 1 :(得分:3)

我认为您可以使用一些临时/变量表,并使用here中的解决方案:

declare @Temp table (rn int identity(1, 1) primary key, dept varchar(128), Total int)

insert into @Temp (dept, Total)
select
    dept, count(*) as Total
from SR
group by dept

;with cte as (
    select T.dept, T.Total, T.Total as Cumulative, T.rn
    from @Temp as T
    where T.rn = 1
    union all
    select T.dept, T.Total, T.Total + C.Cumulative as Cumulative, T.rn
    from cte as C
        inner join @Temp as T on T.rn = C.rn + 1
)
select C.dept, C.Total, C.Cumulative
from cte as C
option (maxrecursion 0)

<强> sql fiddle demo

还有其他一些解决方案,但我认为这个解决方案对SQL Server 2008来说速度最快。