這可能是你追求的:
with tablea as (select to_date('06/07/2015', 'dd/mm/yyyy') dt, 0 value from dual union all
select to_date('05/07/2015', 'dd/mm/yyyy') dt, 0 value from dual union all
select to_date('04/07/2015', 'dd/mm/yyyy') dt, 0 value from dual union all
select to_date('03/07/2015', 'dd/mm/yyyy') dt, 0 value from dual union all
select to_date('02/07/2015', 'dd/mm/yyyy') dt, 0 value from dual union all
select to_date('01/07/2015', 'dd/mm/yyyy') dt, 100 value from dual),
tableb as (select to_date('03/07/2015', 'dd/mm/yyyy') dt, 2 value from dual union all
select to_date('01/07/2015', 'dd/mm/yyyy') dt, 3 value from dual)
select ta.dt,
last_value(decode(ta.value, 0, null, ta.value) ignore nulls) over (order by ta.dt)
+ sum(tb.value) over (order by ta.dt) new_value
from tablea ta
left outer join tableb tb on (ta.dt = tb.dt)
order by ta.dt desc;
DT NEW_VALUE
---------- ----------
06/07/2015 105
05/07/2015 105
04/07/2015 105
03/07/2015 105
02/07/2015 103
01/07/2015 103
但是,你不說經過一系列的零時,有一個在一個非零值,會發生什麼價值觀,很難說這是否會按照你在這種情況下的預期行事。例如,使用相同的數據,但tablea.value = 200爲7月4日:
with tablea as (select to_date('06/07/2015', 'dd/mm/yyyy') dt, 0 value from dual union all
select to_date('05/07/2015', 'dd/mm/yyyy') dt, 0 value from dual union all
select to_date('04/07/2015', 'dd/mm/yyyy') dt, 0 value from dual union all
select to_date('03/07/2015', 'dd/mm/yyyy') dt, 200 value from dual union all
select to_date('02/07/2015', 'dd/mm/yyyy') dt, 0 value from dual union all
select to_date('01/07/2015', 'dd/mm/yyyy') dt, 100 value from dual),
tableb as (select to_date('03/07/2015', 'dd/mm/yyyy') dt, 2 value from dual union all
select to_date('01/07/2015', 'dd/mm/yyyy') dt, 3 value from dual)
select ta.dt,
last_value(decode(ta.value, 0, null, ta.value) ignore nulls) over (order by ta.dt)
+ sum(tb.value) over (order by ta.dt) new_value
from tablea ta
left outer join tableb tb on (ta.dt = tb.dt)
order by ta.dt desc;
DT NEW_VALUE
---------- ----------
06/07/2015 205
05/07/2015 205
04/07/2015 205
03/07/2015 105
02/07/2015 103
01/07/2015 103
你必須更新你的問題涵蓋所有情形,如果我的查詢不會對你以後是什麼和你不能自己解決如何修改它。
**請儘快給我查詢。**? –