معرفی مساله:
Running Totals به معنای حاصل جمع (summation)
تمام مقادیر سطرجاری همراه با سطرهای قبلی در یک دنباله (sequence)
از اعداد است. بطور مثال
seq_nbr
value summation
----------- ----------- -----------
1 5 5 (5)
3 8 13 (5 + 8)
4 4
17
(5 + 8 + 4)
8 2
19
(5 + 8 + 4 + 2)
11 6
25
(5 + 8 + 4 + 2 + 6)
حل مساله:
declare @t
table
(seq_nbr
integer not
null primary
key,
value integer
not null);
insert
into @t
(seq_nbr,
value)
values
(1,5),
(3,8),
(4,4),
(8,2),
(11,6);
with noGaps
as
(
select
row_number()
over(order
by seq_nbr asc)
as seq_nbr,
value
from @t
),
cteSource (seq_nbr,
value, summation)
as
(
select seq_nbr,
value,
value as summation
from noGaps
where seq_nbr
= 1
union all
select
g.seq_nbr, g.value,
c.summation
+ g.value
as summation
from cteSource
as c
inner
join noGaps g
on c.seq_nbr
+ 1 = g.seq_nbr
)
select
* from
cteSource
option (maxrecursion 0);