每组每个时间间隔的滚动总和

时间:2014-03-10 14:08:10

标签: tsql sql-server-2008-r2

表,数据和任务如下。 有关演示数据和估算结果,请参阅SQL-Fiddle-Link

create table "data" 
(
  "item" int
  , "timestamp" date
  , "balance" float
  , "rollingSum" float
)

insert into "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 )

我需要在定义的时间间隔内获取所有行。上表没有为每个可能的日期保留每个项目的记录 - 仅记录应用更改的日期( 可能每个时间戳每个项目有n行) 如果给定的时间间隔与存储的时间戳不完全相符,则应将startdate之前的最新时间戳(最近的最小邻居)用作起始余额/滚动总和。

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

我检查了this之类的问题并搜索了很多内容,但还没有找到解决方案。

我不认为扩展每个项目每个缺失日期一行的“数据”表是个好主意,因此完整的时间间隔(每个项目的最小日期< ----->最新日期可能会扩大好几年了。

提前致谢!

2 个答案:

答案 0 :(得分:0)

select sum(balance)  
from table  
where timestamp >= (select max(timestamp) from table where timestamp <= 'startdate')
  and timestamp <= 'enddate'

不知道滚和的意思。

答案 1 :(得分:0)

这是一次尝试。似乎它给出了正确的结果,而不是那么美丽。在sqlserver 2012 +中会更容易:

declare @from date = '2014-02-13' 
declare @to date = '2014-02-20'
;with x as
(
select 
item, timestamp, balance, row_number() over (partition by item order by timestamp, balance) rn
from (select item, timestamp, balance from data 
union all
select distinct item, @from, null from data) z
where timestamp <= @to
)
, y as
(
  select item, 
  timestamp, 
  coalesce(balance, rollingsum) balance , 
  a.rollingsum, 
  rn
from x d
cross apply
(select sum(balance) rollingsum from x where rn <= d.rn and d.item = item) a
where timestamp between '2014-02-13' and '2014-02-20'

)
select item, timestamp, balance, rollingsum from y
where rollingsum is not null
order by item, rn, timestamp

结果:

item  timestamp   balance  rollingsum
1     2014-02-13  -10,00   -10,00
1     2014-02-15  5,00     -5,00
1     2014-02-20  2,00     -3,00
2     2014-02-13  15,00    15,00
2     2014-02-16  15,00    30,00