这个问题是升级版本here。吉奥戈斯贝佐斯先生提供的解决方案运行良好。但是,我升级了我的需求,以按产品ID筛选(使用group by我假设)。新桌子现在看起来像这样

ID   |   BALANCE   |   ACTION_QTY   |   ACTION_TYPE |   PRODUCT_ID   |
---------------------------------------------------------------------|
1    |     0       |       3        |       ADD     |       12       |
2    |     0       |       2        |       DEDUCT  |       12       |
3    |     0       |       6        |       ADD     |       11       |
4    |     0       |       3        |       ADD     |       11       |
5    |     0       |       1        |       DEDUCT  |       12       |
6    |     0       |       7        |       ADD     |       15       |
7    |     0       |       1        |       DEDUCT  |       15       |
8    |     0       |       3        |       ADD     |       15       |
9    |     0       |       7        |       DEDUCT  |       11       |
10   |     0       |       9        |       ADD     |       12       |

SQL FIDDLE
如何根据产品ID和订单ID添加/减去余额字段?@Giorgos Betsos的SQL:
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

我试图按产品ID添加组,但结果不正确。
我想要的结果如下:
ID   |   BALANCE   |   ACTION_QTY   |   ACTION_TYPE |   PRODUCT_ID   |
---------------------------------------------------------------------|
1    |     3       |       3        |       ADD     |       12       |
2    |     1       |       2        |       DEDUCT  |       12       |
3    |     6       |       6        |       ADD     |       11       |
4    |     9       |       3        |       ADD     |       11       |
5    |     0       |       1        |       DEDUCT  |       12       |
6    |     7       |       7        |       ADD     |       15       |
7    |     6       |       1        |       DEDUCT  |       15       |
8    |     9       |       3        |       ADD     |       15       |
9    |     2       |       7        |       DEDUCT  |       11       |
10   |     9       |       9        |       ADD     |       12       |

请帮帮我,
非常感谢

最佳答案

您可以在相关查询中使用CASE EXPRESSION完成此操作:

SELECT s.id,
       (SELECT sum(CASE WHEN t.action_type = 'ADD' THEN t.action_qty ELSE -1*t.action_qty END)
        FROM (YourQuery) t
        WHERE t.id <= s.id and t.product_id = s.product_id),
       s.action_qty,s.action_type,s.product_id
FROM (YourQuery) s
ORDER BY s.id

案例将决定是对值求和,还是用value*-1列中的值对action_type求和。

关于mysql - SQL:基于带有GROUP BY条件的字段类型的ADD和MINUS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37807316/

10-09 05:47
查看更多