Ecco due versioni per fare questo. Ho provato con 100000 righe distribuite su 6000 giorni su un computer veramente lento con memoria insufficiente, e questo dimostra che la versione cte è più veloce della versione loop. Le altre versioni suggerite qui (finora) sono molto più lente, a condizione che abbia compreso correttamente il problema.
CTE ricorsiva (10 secondi)
-- 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)
Loop (14 secondi)
-- 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
Modifica 1 La versione veramente veloce
The quirky update
-- 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
Oh, vedo [SQL-Server] è riservato per MS: o molto fuorviante. – vbence
@vbence: sembra che tu non abbia sentito parlare di SQL Server. http://en.wikipedia.org/wiki/Microsoft_SQL_Server –
@ p.campbell Wow .. tanta ostilità in un commento così breve. – vbence