[英]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
即可。
我認為您可以為此使用一些臨時/變量表,並從此處使用解決方案:
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 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.