我需要计算一列 ( Transparencia) 作为前一行Transparencia和Dif值的总和。最初,只有第一行在列中有值Transparencia:
Account ------ Year_ ---- Month_ ---- Transparencia ---- Dif
--------------------------------------------------------------
'4030003'------ 2018 ---- 5 ---- 100 ---- -2
'4040001'------ 2018 ---- 5 ---- null ---- -4
'4040002'------ 2018 ---- 5 ---- null ---- 3
...
Account(N-1)------ 2018 ---- 5 ---- x ---- 8
Account(N)------ 2018 ---- 5 ---- x + 8 ---- 11
目的是获得以下内容:
Account ------ Year_ ---- Month_ ---- Transparencia ---- Dif
--------------------------------------------------------------
'4030003'------ 2018 ---- 5 ---- 100 ---- -2
'4040001'------ 2018 ---- 5 ---- 98 ---- -4
'4040002'------ 2018 ---- 5 ---- 94 ---- 3
...
Account(N-1)------ 2018 ---- 5 ---- x ---- 8
Account(N)------ 2018 ---- 5 ---- x + 8 ---- 11
在哪里:
- 98 = 100 + (-2) -> (
Transparencia从上一行加上Dif从上一行) - 94 = 98 + (-4) -> (
Transparencia从上一行加上Dif从上一行) - x = 上一行的“Transparencia” + 上一行的“Dif”
- x + 8 = 上一行的“Transparencia” + 8(上一行的“Dif”)
我尝试的解决方案是:
select
tmp.Account, tmp.Year_, tmp.Month_,Dif,
case
when Transparencia is null
then (lag(Transparencia, 1, 0) over (order by Account) -
lag(Dif, 1, 0) over (order by Account))
else Transparencia
end Transparencia
from
(select
Account,
nryear as Year_, nrperiod as Month_,
Dif, Transparencia
from
repaca
where
nrperiod = 5) tmp
但是,这将返回以下结果:
Account ------ Year_ ---- Month_ ---- Transparencia ---- Dif
'4030003'------ 2018 ---- 5 ---- 100 ---- -2
'4040001'------ 2018 ---- 5 ---- 98 ---- -4
'4040002'------ 2018 ---- 5 ---- null ---- 3
我只需要使用一个SELECT,而不是一个存储过程或类似的东西来实现这一点。任何帮助将不胜感激。
提前致谢