好吧,我有一个让我无法解决的头脑。 总新手:) 如果它们出现在计算中,我需要计算库存项目数量并检测负值:
inquantity | outquantity
100 | 0
10 | 0
0 | 50
0 | 100
20 | 0
0 | 80
15 | 0
100 | 0
我需要计算Quty:
inquantity | outquantity | Quty
100 | 0 | 100
10 | 0 | 110
0 | 50 | 60
0 | 100 | -40
20 | 0 | -20
0 | 80 | -100
15 | 0 | -85
100 | 0 | 15
我该怎么做?
关于Abhik的帖子:
select
id ,
inquantity,
outquantity,
@qty:= (@qty+inquantity)-outquantity as qty
from quantity,(select @qty:= 0 )r
order by id;
是否有可能在productid change上重置变量@qty?
+----+-----------+------------+-------------+------+
| id | productid | inquantity | outquantity | qty |
+----+-----------+------------+-------------+------+
| 1 | 1 | 100 | 0 | 100 |
| 2 | 1 | 10 | 0 | 110 |
| 3 | 1 | 0 | 50 | 60 |
| 4 | 1 | 0 | 100 | -40 |
| 5 | 2 | 20 | 0 | 20 |
| 6 | 2 | 0 | 80 | -60 |
| 7 | 2 | 15 | 0 | -45 |
| 8 | 3 | 100 | 0 | 100 |
+----+-----------+------------+-------------+------+
答案 0 :(得分:2)
如您所述,您考虑以下内容id
mysql> select * from quantity ;
+------+------------+-------------+
| id | inquantity | outquantity |
+------+------------+-------------+
| 1 | 100 | 0 |
| 2 | 10 | 0 |
| 3 | 0 | 50 |
| 4 | 0 | 100 |
| 5 | 20 | 0 |
| 6 | 0 | 80 |
| 7 | 15 | 0 |
| 8 | 100 | 0 |
+------+------------+-------------+
我们可以获得所需的结果
select
id ,
inquantity,
outquantity,
@qty:= (@qty+inquantity)-outquantity as qty
from quantity,(select @qty:= 0 )r
order by id;
输出为
+------+------------+-------------+------+
| id | inquantity | outquantity | qty |
+------+------------+-------------+------+
| 1 | 100 | 0 | 100 |
| 2 | 10 | 0 | 110 |
| 3 | 0 | 50 | 60 |
| 4 | 0 | 100 | -40 |
| 5 | 20 | 0 | -20 |
| 6 | 0 | 80 | -100 |
| 7 | 15 | 0 | -85 |
| 8 | 100 | 0 | 15 |
+------+------------+-------------+------+
答案 1 :(得分:0)
这个想法是获得累积总和。假设您有一个提供订购信息的列,您可以使用子查询或变量执行此操作。后者应该更有效率:
select t.*, (cumei - cumeo) as diff
from (select t.*, (@i := @i + inquantity) as cumei,
(@o := @o + outquantity) as cumeo
from table t
(select @i := 0, @o := 0) vars
order by id
) t
where (cumei - cumeo) < 0;