LAG的使用-SQL Server 2014
我需要计算一列(LAG的使用-SQL Server 2014,sql,sql-server-2014,lag,Sql,Sql Server 2014,Lag,我需要计算一列(Transparencia)作为前一行的Transparencia和Dif值之和。最初,只有第一行在Transparencia列中有值: Account ------ Year_ ---- Month_ ---- Transparencia ---- Dif -------------------------------------------------------------- '4030003'------ 2018 ---- 5 ---
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=“透明”来自上一行+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
我只需要使用选择
,而不是存储过程或类似方法来实现这一点。任何帮助都将不胜感激
提前感谢您不需要lag()
。你想要累积的总和。由于该值为NULL
,因此可以使用max()
简化获取第一个值的过程。因此:
select r.*,
(max(Transparencia) over () +
sum(diff) over (order by year, month)
) as new_Transparencia
from repaca r;
您也可以将其表述为:
select r.*,
sum(coalesce(Transparencia, 0) + diff) over (order by year, month) as new_Transparencia
from repaca r;
编辑:
以上是使用错误的顺序。这似乎是:
select r.*,
(max(Transparencia) over (partition by year, month) +
sum(diff) over (partition by year, month order by account)
) as new_Transparencia
from repaca r;
非常感谢您的回答,但是您的代码总结了一年内所有差异的初始Transparencia,但我只需要Transparencia等于上一行的“Transparencia”+上一行的差异(只有前一行)。这就是为什么我使用LAG,只访问前一行的信息。@Andrew8902。我第一次误解了数据。你确实想要一个累积的总和,但它需要使用正确的列。再次感谢你的帮助,但我仍然没有得到我需要的结果。在我的示例中,采用previous Transparencia+previous Diff的规则仅适用于n>1的行。第一排,我只需要透明胶片。