首页 > 解决方案 > LAG 的使用 - SQL Server 2014

问题描述

我需要计算一列 ( Transparencia) 作为前一行TransparenciaDif值的总和。最初,只有第一行在列中有值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  

在哪里:

我尝试的解决方案是:

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,而不是一个存储过程或类似的东西来实现这一点。任何帮助将不胜感激。

提前致谢

标签: sqlsql-server-2014lag

解决方案


你不想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;

推荐阅读