SQL 上一行+当前行计算

SQL calculation with previous row + current row

我想根据excel文件进行计算。我使用 LAG 成功获得了第一条记录中的 2 条(您可以在第二张屏幕截图中查看)。我不知道如何从现在开始并需要帮助。我只需要计算列采用其以前的数据。我想自动计算所有日期。我还尝试为计算创建一个 LAG,但手动进行,结果是 +1 行更多数据而不是 NULL。很头疼。

LAG(Data ingested, 1) OVER ( ORDER BY DATE ASC ) AS LAG

您似乎想要累计金额:

select t.*,
       (sum(reconciliation + aves - microa) over (order by date) -
        first_value(aves - microa) over (order by date)
       ) as calculation
from CalcTable t;

Here 是 SQL Fiddle.

编辑:

根据您的意见,您只需定义一个组:

select t.*,
       (sum(reconciliation + aves - microa) over (partition by grp order by date) -
        first_value(aves - microa) over (partition by grp order by date)
       ) as calculation
from (select t.*,
             count(nullif(reconciliation, 0)) over (order by date) as grp
      from CalcTable t
     ) t
order by date;

在我看来,这可以使用“差距和孤岛”方法来解决。当 Reconciliation>0 时,则创建间隙。 SUM(GAP) OVER 将间隙转换为岛屿分组。在外部查询中,'sum_over' 列(对应于 'Calculation')是按岛屿分组划分的累积总和。

with 
gap_cte as (
    select *, case when [Reconciliation]>0 then 1 else 0 end gap
    from CalcTable),
grp_cte as (
    select *, sum(gap) over (order by [Date]) grp
    from gap_cte)
select *, sum([Reconciliation]+
               (case when gap=1 then 0 else Aves end)-
               (case when gap=1 then 0 else Microa end)) 
               over (partition by grp order by [Date]) sum_over
from grp_cte;

[编辑] CASE 语句可以交叉应用

with 
grp_cte as (
    select c.*, v.gap, sum(v.gap) over (order by [Date]) grp
    from #CalcTable c
         cross apply (values (case when [Reconciliation]>0 then 1 else 0 end)) v(gap))
select *, sum([Reconciliation]+
               (case when gap=1 then 0 else Aves end)-
               (case when gap=1 then 0 else Microa end)) 
               over (partition by grp order by [Date]) sum_over
from grp_cte;

Here 是一个 fiddle