如何根据前一行的值更新值

How to update a value based on previous row's value

我有一个如下所示的 table(sql 服务器 2019):

Name  Total  Payment   BalanceForward     Date
A     NULL   NULL      0                  NULL
A     20     40        NULL               01-2021
A     100    50        NULL               02-2021
A     50     80        NULL               03-2021
B     NULL   NULL      30                 NULL
B     50     50        NULL               01-2021
B     50     80        NULL               02-2021
B     50     40        NULL               03-2021
C     NULL   NULL      100                NULL
........

我想要更新“BalanceForward”列,因为它会有 Balance Forward of previous row + (current row's Total - current row's Payment)

预期输出:

Name  Total  Payment   BalanceForward   Date
A     NULL   NULL      0                NULL
A     20     40        -20              01-2021
A     100    50        30               02-2021
A     50     80        0                03-2021
B     NULL   NULL      30               NULL
B     50     50        30               01-2021
B     50     80        0                02-2021
B     50     40        10               03-2021
C     NULL   NULL      100              NULL
.......

最好的提供方式是什么?任何帮助将不胜感激。

您似乎想要实施 运行 总数。您可以使用 sum over() window 函数和 updatable CTE 来完成此操作,如下所示:

with bf as (
    select *,
        Sum(total-payment) over(partition by name order by date)
        + sum(balanceforward) over(partition by name order by date) newbf
    from t
)
update bf set balanceforward=newbf
where balanceforward is null

示例DB<>Fiddle

这是 Stu 回答的更可靠版本。您可以 运行 两次,任意次数都具有相同的输出。

with bf as (
    select *, sum(total-payment) over(partition by name order by date) + first_value(balanceforward) over(partition by name order by date) newbf
    from t
)
update bf set balanceforward=newbf
where date is not null;