我有一个包含四列的表(id,Creditor,Debit,Balance) 我想工作
-----------------------------
| id |Creditor|Debit|Balance|
----------------------------
| 1 | 100 |null | null |
| 2 | 50 |null | null |
| 3 | null | 100 | null |
| 4 | 50 |null | null |
| 5 | null | 20 | null |
| 6 | null | 10 | null |
| 7 | null | 100 | null |
| 8 | 200 |null | null |
-----------------------------
债权人 - 借记+上一行余额
我怎样才能实现这个目标
预期产出
-----------------------------
| id |Creditor|Debit|Balance|
----------------------------
| 1 | 100 |null | 100 |
| 2 | 50 |null | 150 |
| 3 | null | 100 | 50 |
| 4 | 50 |null | 100 |
| 5 | null | 20 | 80 |
| 6 | null | 10 | 70 |
| 7 | null | 100 | -30 |
| 8 | 200 |null | 170 |
-----------------------------
答案 0 :(得分:0)
您可以使用累积总和:
select (coalesce(sum(creditor) over (order by id), 0) +
coalesce(sum(debitor) over (order by id), 0)
) as balance
要设置该值,您可以使用可更新的CTE:
with toupdate as (
select t.*
(coalesce(sum(creditor) over (order by id), 0) +
coalesce(sum(debitor) over (order by id), 0)
) as new_balance
from t
)
update toupdate
set balance = new_balance;