我的表格如下所示:
表A
ID | BALANCE | ACTION_QTY | ACTION_TYPE |
----------------------------------------------------
1 | 0 | 3 | ADD |
2 | 0 | 2 | DEDUCT |
3 | 0 | 6 | ADD |
4 | 0 | 3 | ADD |
5 | 0 | 1 | DEDUCT |
6 | 0 | 7 | ADD |
7 | 0 | 8 | DEDUCT |
8 | 0 | 3 | ADD |
9 | 0 | 7 | DEDUCT |
10 | 0 | 9 | ADD |
如何根据 ACTION_TYPE 字段和 ACTION_QTY 字段
的总和和扣除来更新 BALANCE 字段我想要的结果如下:
ID | BALANCE | ACTION_QTY | ACTION_TYPE |
----------------------------------------------------
1 | 3 | 3 | ADD |
2 | 1 | 2 | DEDUCT |
3 | 7 | 6 | ADD |
4 | 10 | 3 | ADD |
5 | 9 | 1 | DEDUCT |
6 | 16 | 7 | ADD |
7 | 8 | 8 | DEDUCT |
8 | 11 | 3 | ADD |
9 | 4 | 7 | DEDUCT |
10 | 13 | 9 | ADD |
任何帮助都会很棒。
答案 0 :(得分:4)
您可以使用变量来保存累积金额:
SELECT ID,
@s := IF(ACTION_TYPE='ADD', @s + ACTION_QTY, @s - ACTION_QTY) AS BALANCE,
ACTION_QTY,
ACTION_TYPE
FROM tableA
CROSS JOIN (SELECT @s := 0) AS var
ORDER BY ID
以上查询假设只有两种类型的ACTION_TYPE
值,即'ADD'
和'DEDUCT'
。因此,如果ACTION_TYPE
不等于'ADD'
,那么它等于'DEDUCT'
。