简体   繁体   English

SQL 累计计数

[英]SQL Cumulative Count

I have table with departments.我有部门表。 I need to count how many people are within which dept.我需要计算哪个部门有多少人。 This is easily done by这很容易通过

SELECT DEPT,
       COUNT(*) as 'Total'
    FROM SR
    GROUP BY DEPT;

Now I need to also do cumulative count as below:现在我还需要进行如下累计计数:

在此处输入图像描述

I have found some SQL to count running total, but not case like this one.我找到了一些 SQL 来计算总计,但不是这样的。 Could you provide me some advice in this case, please?在这种情况下,你能给我一些建议吗?

Here's a way to do it with a CTE instead of a cursor:这是一种使用 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

Note that this is ordering by descending Count like your sample result does.请注意,这是按Count降序排序,就像您的示例结果一样。 If there's some other column that's not shown that should be used for ordering just replace Count in each of the ORDER BY clauses.如果还有其他一些未显示的列应该用于排序,只需在每个ORDER BY子句中替换Count即可。

SQL Fiddle Demo SQL 小提琴演示

I think you can use some temporary / variable table for this, and use solution from 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 小提琴演示

There're some other solutions, but this one is fastest for SQL Server 2008, I think.还有一些其他的解决方案,但我认为这个对于 SQL Server 2008 来说是最快的。

If it is possible to add an identity column to the table - then the solution is easier;如果可以在表中添加标识列 - 那么解决方案会更容易;

create table #SQLCumulativeCount
(
 id int identity(1,1),
 Dept varchar(100),
 Count int
)
insert into #SQLCumulativeCount (Dept,Count) values ('PMO',106)
insert into #SQLCumulativeCount (Dept,Count) values ('Finance',64)
insert into #SQLCumulativeCount (Dept,Count) values ('Operations',41)
insert into #SQLCumulativeCount (Dept,Count) values ('Infrastructure',22)
insert into #SQLCumulativeCount (Dept,Count) values ('HR',21)

select *,
   sum(Count) over(order by id rows unbounded preceding) as Cumulative 
from #SQLCumulativeCount
with Base as (
select 
    dept, 
    count, 
    ROW_NUMBER() OVER(order by count desc) as RowNum
from SR
)
select 
    dept, 
    count, 
    sum(count) over(order by RowNum) as Cumulative
from Base

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM