tsql - Rolling sum per time interval per group -
table, data , task follows. see sql-fiddle-link demo-data , estimated results.
create table "data" ( "item" int , "timestamp" date , "balance" float , "rollingsum" float ) insert "data" ( "item", "timestamp", "balance", "rollingsum" ) values ( 1, '2014-02-10', -10, -10 ) , ( 1, '2014-02-15', 5, -5 ) , ( 1, '2014-02-20', 2, -3 ) , ( 1, '2014-02-25', 13, 10 ) , ( 2, '2014-02-13', 15, 15 ) , ( 2, '2014-02-16', 15, 30 ) , ( 2, '2014-03-01', 15, 45 )
i need rows in defined time interval. above table doesn't hold record per item each possible date - dates on changes applied recorded ( is possible there n rows per timestamp per item ) if given interval not fit on stored timestamps, latest timestamp before startdate ( nearest smallest neighbour ) should used start-balance/rolling-sum.
estimated results ( time interval: startdate = '2014-02-13', enddate = '2014-02-20' ) "item", "timestamp" , "balance", "rollingsum" 1 , '2014-02-13' , -10 , -10 1 , '2014-02-15' , 5 , -5 1 , '2014-02-20' , 2 , -3 2 , '2014-02-13' , 15 , 15 2 , '2014-02-16' , 15 , 30
i checked questions this , googled lot, didn't found solution yet.
i don't think it's idea extend "data" table 1 row per missing date per item, complete interval ( smallest date <-----> latest date per item may expand on several years ).
thanks in advance!
select sum(balance) table timestamp >= (select max(timestamp) table timestamp <= 'startdate') , timestamp <= 'enddate'
don't know mean rolling-sum.
Comments
Post a Comment