如果我正确理解您的要求,
SQL小提琴
Oracle 11g R2 模式设置:
CREATE TABLE months
("MON" date, "VALUE" int)
;
INSERT ALL
INTO months ("MON", "VALUE")
VALUES (date '2013-11-01', 20)
INTO months ("MON", "VALUE")
VALUES (date '2014-03-01', 10)
SELECT * FROM dual
;
查询 1:
with months_interval as (
select date '2013-05-01' interval_start,
max(mon) interval_end
from months
)
, all_months as (
select add_months(m.interval_start,level-1) mon
from months_interval m
connect by level <= months_between(interval_end, interval_start) + 1
), data_to_sum as (
select am.mon,
decode(am.mon, first_value(am.mon) over(order by am.mon), 10, m.value) value
from months m, all_months am
where am.mon = m.mon(+)
)
select mon, value, sum(value) over(order by mon) cumulative
from data_to_sum
order by 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 |
这可能在性能方面略微次优(查询月份表两次等)并且应该进行优化,但想法是这样的 - 预先生成月份列表(我假设您的间隔开始以某种方式固定),将其加入您的数据,使用解析求和函数。