Вот две версии для этого.Я протестировал 100000 строк, распределенных за 6000 дней, на очень медленном компьютере с недостаточным объемом памяти, и это показывает, что версия cte быстрее, чем версия цикла.Другие версии, предложенные здесь (пока), намного медленнее, при условии, что я правильно понял проблему.
Рекурсивный CTE (10 секунд)
-- Table variable to hold count for each day
declare @DateCount table(d int, c int, rn int)
insert into @DateCount
select
datediff(d, 0, date_created) as d,
count(*) as c,
row_number() over(order by datediff(d, 0, date_created)) as rn
from reg
group by datediff(d, 0, date_created)
-- Recursive cte using @DateCount to calculate the running sum
;with DateSum as
(
select
d, c, rn
from @DateCount
where rn = 1
union all
select
dc.d, ds.c+dc.c as c, dc.rn
from DateSum as ds
inner join @DateCount as dc
on ds.rn+1 = dc.rn
)
select
dateadd(d, d, 0) as date_created,
c as total_num
from DateSum
option (maxrecursion 0)
Петля (14 секунд)
-- Table variable to hold count for each day
declare @DateCount table(d int, c int, rn int, cr int)
insert into @DateCount
select
datediff(d, 0, date_created) as d,
count(*) as c,
row_number() over(order by datediff(d, 0, date_created)) as rn,
0
from reg
group by datediff(d, 0, date_created)
declare @rn int = 1
-- Update cr with running sum
update dc set
cr = dc.c
from @DateCount as dc
where rn = @rn
while @@rowcount = 1
begin
set @rn = @rn + 1
update dc set
cr = dc.c + (select cr from @DateCount where rn = @rn - 1)
from @DateCount as dc
where rn = @rn
end
-- Get the result
select
dateadd(d, d, 0) as date_created,
cr as total_num
from @DateCount
Редактировать 1 Действительно быстрая версия
Причудливое обновление
-- Table variable to hold count for each day
declare @DateCount table(d int primary key, c int, cr int)
insert into @DateCount
select
datediff(d, 0, date_created) as d,
count(*) as c,
0
from reg
group by datediff(d, 0, date_created)
declare @rt int = 0
declare @anchor int
update @DateCount set
@rt = cr = @rt + c,
@anchor = d
option (maxdop 1)
-- Get the result
select
dateadd(d, d, 0) as date_created,
cr as total_num
from @DateCount
order by d