繁体   English   中英

SQL 累计计数

[英]SQL Cumulative Count

我有部门表。 我需要计算哪个部门有多少人。 这很容易通过

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

现在我还需要进行如下累计计数:

在此处输入图像描述

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

这是一种使用 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降序排序,就像您的示例结果一样。 如果还有其他一些未显示的列应该用于排序,只需在每个ORDER BY子句中替换Count即可。

SQL 小提琴演示

我认为您可以为此使用一些临时/变量表,并从此处使用解决方案:

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 小提琴演示

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

如果可以在表中添加标识列 - 那么解决方案会更容易;

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