我有一个包含四列( 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 |
-----------------------------
您可以使用累积总和:
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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句