How to generate a compounded view of data over time in Oracle SQL -
say have base number 10 , table has value of 20 associated november 2013, , value of 10 associated march 2014. want populate list of months, , compounded value. may-november 2013, value should 10, between nov , mar, value should 10+20 , afterwards should 10+20+10.
so in table have following
month value nov-2013 20 mar-2014 10 i'd have select statement somehow returns. there's initial value of 10, hard-coded base.
month value may-2013 10 jun-2013 10 jul-2013 10 aug-2013 10 sep-2013 10 oct-2013 10 nov-2013 30 dec-2013 30 jan-2014 30 feb-2014 30 mar-2014 40 is doable?
in case understand requirements correctly,
oracle 11g r2 schema setup:
create table months ("mon" date, "value" int) ; insert months ("mon", "value") values (date '2013-11-01', 20) months ("mon", "value") values (date '2014-03-01', 10) select * dual ; query 1:
with months_interval ( select date '2013-05-01' interval_start, max(mon) interval_end months ) , all_months ( select add_months(m.interval_start,level-1) mon months_interval m connect level <= months_between(interval_end, interval_start) + 1 ), data_to_sum ( select am.mon, decode(am.mon, first_value(am.mon) over(order am.mon), 10, m.value) value months m, all_months am.mon = m.mon(+) ) select mon, value, sum(value) over(order mon) cumulative data_to_sum order 1 | mon | value | cumulative | ---------------------------------------------------------- | may, 01 2013 00:00:00+0000 | 10 | 10 | | june, 01 2013 00:00:00+0000 | (null) | 10 | | july, 01 2013 00:00:00+0000 | (null) | 10 | | august, 01 2013 00:00:00+0000 | (null) | 10 | | september, 01 2013 00:00:00+0000 | (null) | 10 | | october, 01 2013 00:00:00+0000 | (null) | 10 | | november, 01 2013 00:00:00+0000 | 20 | 30 | | december, 01 2013 00:00:00+0000 | (null) | 30 | | january, 01 2014 00:00:00+0000 | (null) | 30 | | february, 01 2014 00:00:00+0000 | (null) | 30 | | march, 01 2014 00:00:00+0000 | 10 | 40 | this 1 suboptimal performance-wise (queries months table twice etc.) , should optimized, idea - pregenerate list of months (i assumed interval start somehow fixed), left join data, use analytic sum function.
Comments
Post a Comment