sql - LAG 的使用 - SQL Server 2014
问题描述
我需要计算一列 ( 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
,而不是一个存储过程或类似的东西来实现这一点。任何帮助将不胜感激。
提前致谢
解决方案
你不想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;
推荐阅读
- c# - SqlCommand Parameter & CommandText 声明的顺序是否重要?
- c++ - 遍历 YAML::Node 时如何获取当前节点的父节点?
- c# - 在 C# 中反序列化具有 CamelCase 和 snake_case 命名键的 JSON
- aws-lambda - 为什么在执行调用 cognito lambda 触发 PostConfirmation 和 PreTokenGeneration 的开玩笑测试时会出现随机错误?
- dart - 有没有办法从命令行应用程序注入键盘事件?
- javascript - 如何让我的 html 输入元素影响我的 javascript 类对象值(字符名称)
- python - 有没有一种简单有效的方法来使用 pygame 为平台游戏编写 python 中的跳跃和重力逻辑代码?
- c++ - 当我从文件中读取时,我得到了控制字符
- java - Derby 如何在现有列上添加 NOT NULL 约束
- selenium - 如何在python中总是将+1添加到0