簡體   English   中英

SQL數量計算

[英]SQL quantity calculation

好吧,我有一個無法解決的問題。 新手總數:)我需要計算庫存項目的數量,並在計算中出現負值時進行檢測:

inquantity | outquantity
100        |      0
10         |      0
0          |     50
0          |     100
20         |      0
0          |     80
15         |      0
100        |      0

我需要計算數量:

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更改時重置變量@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  |
+----+-----------+------------+-------------+------+

考慮到以下提到的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 |
+------+------------+-------------+------+

這個想法是獲得累計和。 假設您有一列提供訂購信息,則可以使用子查詢或變量來完成此操作。 后者應該更有效:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM