3

Say I have a base number 10 and a table that has a value of 20 associated to November 2013, and a value of 10 associated to March 2014. I want to populate a list of all months, and their compounded value. So from May-November 2013, the value should be 10, then between Nov and Mar, the value should be 10+20 and afterwards it should be 10+20+10.

So in a table I have the following

MONTH     VALUE
Nov-2013  20
Mar-2014  10

I'd like to have a select statement that somehow returns. There's an initial value of 10, hard-coded as the 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 this doable?

4

1 回答 1

3

如果我正确理解您的要求,

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 |

这可能在性能方面略微次优(查询月份表两次等)并且应该进行优化,但想法是这样的 - 预先生成月份列表(我假设您的间隔开始以某种方式固定),将其加入您的数据,使用解析求和函数。

于 2013-05-09T16:29:42.150 回答