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
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)
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
3条答案
按热度按时间whlutmcx1#
以下是使用CTE而不是光标来实现这一点的方法:
请注意,这是按照
Count
的降序进行排序的,就像您的示例结果一样。如果有其他列没有显示应该用于订购,只需在每个ORDER BY
子句中替换Count
即可。SQL小提琴演示
htrmnn0y2#
我认为您可以为此使用一些临时/变量表,并从以下位置使用解决方案:
SQL小提琴演示
还有其他一些解决方案,但我认为这是SQL Server2008最快的解决方案。
falq053o3#
如果可以将标识列添加到表中-那么解决方案就更容易了;