sql server 2008 - cumulative totals based on condition -
i trying cumulative totals based on criteria. below dummy sample data set. cumulative time based on indicator
id
. when indicator
continuously 1
same id
, sum of duration
. if becomes 0
restart.
id duration indicator cumm_duration 1 30 0 30 1 30 1 60 1 30 0 30 1 30 0 30 1 30 1 60 1 30 0 30 1 30 0 30 1 30 0 30 1 30 0 30 1 30 0 30 1 30 0 30 1 30 0 30 1 30 1 60 1 30 1 90 2 30 1 30 2 30 0 30 2 30 0 30 2 30 0 30 2 30 1 60 2 30 0 30 2 30 1 60 2 30 0 30 2 30 0 30 2 30 0 30 2 30 1 60 2 30 1 90 2 30 0 30
data:
declare @t table ( id int , duration int , indicator int ) insert @t values ( 1, 30, 0 ), ( 1, 30, 1 ), ( 1, 30, 0 ), ( 1, 30, 0 ), ( 1, 30, 1 ), ( 1, 30, 0 ), ( 1, 30, 0 ), ( 1, 30, 0 ), ( 1, 30, 0 ), ( 1, 30, 0 ), ( 1, 30, 0 ), ( 1, 30, 0 ), ( 1, 30, 1 ), ( 1, 30, 1 ), ( 2, 30, 1 ), ( 2, 30, 0 ), ( 2, 30, 0 ), ( 2, 30, 0 ), ( 2, 30, 1 ), ( 2, 30, 0 ), ( 2, 30, 1 ), ( 2, 30, 0 ), ( 2, 30, 0 ), ( 2, 30, 0 ), ( 2, 30, 1 ), ( 2, 30, 1 ), ( 2, 30, 0 );
solution1(bruteforce):
with indexed ( select * , row_number() on ( order ( select null ) ) rn @t ), recursion ( select * , duration cumulative indexed rn = 1 union select t.* , case when t.indicator = 1 , t.id = r.id r.cumulative + t.duration else t.duration end indexed t join recursion r on r.rn + 1 = t.rn ) select * recursion option ( maxrecursion 0 )
solution2:
with indexed (select *, row_number() on (order (select null)) rn @t) select *, (select sum(duration) indexed i2 i1.id = i2.id , i2.rn <= i1.rn , i2.rn >= isnull((select top 1 i3.rn indexed i3 i3.indicator = 0 , i3.rn <= i1.rn order i3.rn desc), 0)) indexed i1
Comments
Post a Comment