SQL累计计数

kyvafyod  于 2022-09-18  发布在  Java
关注(0)|答案(3)|浏览(126)

我和各部门都有餐桌。我要数一数哪个部门有多少人。这很容易通过以下方式完成

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

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

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

whlutmcx

whlutmcx1#

以下是使用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小提琴演示

htrmnn0y

htrmnn0y2#

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

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 Server2008最快的解决方案。

falq053o

falq053o3#

如果可以将标识列添加到表中-那么解决方案就更容易了;

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

相关问题