我有下表:
CREATE TABLE `movm` (
`id` INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
`product` INTEGER NOT NULL,
`value` DECIMAL(10, 2) NOT NULL
-- ...
);
还有一些数据:
INSERT INTO `movm`(`product`, `value`) VALUES
(1, 1000),
(1, -200),
(1, 100),
(2, 50),
(2, -10),
(1, 100),
(2, -20);
我希望得到以下结果:
+----+---------+---------+----------+---------+
| id | product | value | previous | current |
+----+---------+---------+----------+---------+
| 1 | 1 | 1000.00 | 0 | 1000 |
| 2 | 1 | -200.00 | 1000 | 800 |
| 3 | 1 | 100.00 | 800 | 900 |
| 6 | 1 | 100.00 | 900 | 1000 |
| 4 | 2 | 50.00 | 0 | 50 |
| 5 | 2 | -10.00 | 50 | 40 |
| 7 | 2 | -20.00 | 40 | 20 |
但始终尊重GROUP BY
产品。
我尝试过以下SQL:
SELECT
`id`,
`product`,
`value`,
@previous := (@current) AS `previous`,
@current := (@current + `value`) AS `current`
FROM
`movm`,
(
SELECT
@previous := 0,
@current := 0
) AS `__movm`;
因为它不尊重小组,它总是对所有内容进行总结,并且没有决胜局。
已经IF(@product != product, @current := 0, NULL)
;工作,但没有那么灵活。而且我还需要跟踪该产品的值,绕过任何订单,如你所见,它们没有排序(我认为这很容易解决在子查询中包装当前的SQL)。
那么:有没有更好的解决方案,我可以使用GROUP BY product
并获得所示的预期结果?