我有一个包含ID,Opening_Balnce和Closing Balance列的表,如下所示。这是我们的客户维护的现有表,而OB则是指需要加/减到前一行cb的金额。例如,如果我从供应商处收到100 rs,则我需要将ob增加100,并将cb添加600。
ID OB CB
===============
1 100 100
2 100 200
3 100 300
4 100 400
5 -100 300
6 100 400
7 100 500
8 -100 400
如果我在中间更新/删除某行,则期末余额应根据先前的行值进行更新。
例如,我要更新ID = 4的OB = 200,因此输出应如下所示:
ID OB CB
===============
1 100 100
2 100 200
3 100 300
4 200 500
5 -100 400
6 100 500
7 100 600
8 -100 500
我已经尝试过一次无法单次运行的sql尝试
UPDATE A
SET OB = 200, CB = OB + PrevCB
FROM A JOIN (SELECT LAG(CB) OVER (ORDER BY ID)PrevCB, ID FROM A) X ON A.ID = X.ID
WHERE A.ID = 4;
UPDATE A
SET CB = OB + PrevCB
FROM A JOIN (SELECT LAG(CB) OVER (ORDER BY ID)PrevCB, ID FROM A) X ON A.ID = X.ID
WHERE A.ID > 4;
答案 0 :(得分:1)
您可以尝试使用SUM
窗口功能。
UPDATE T
SET OB = 200
FROM T
WHERE ID = 4;
UPDATE T
SET CB = val + (SELECT CB FROM T WHERE ID = 3)
FROM T JOIN (
SELECT SUM(OB) over(order by ID) val, ID
FROM T
WHERE ID > 3
) X ON T.ID = X.ID
结果
ID OB CB
===============
1 100 100
2 100 200
3 100 300
4 200 500
5 -100 400
6 100 500
7 100 600
8 -100 500