根据订单更新库存表数量

时间:2015-11-16 04:43:32

标签: mysql sql

我在创建一个sql语句时遇到问题,该语句将根据Inbound orders表更新Inventory表。

入站

OrderID  ProductID  Description  ShipQty
001      2          Apple        3
002      4          Orange       4
003      1          Grape        1
004      2          Apple        6
005      5          Strawberry   3
006      3          Pear         1
007      1          Grape        2

INVENTORY

ProductID  Description  Qty
1          Grape        10
2          Apple        10
3          Pear         10
4          Orange       10
5          Strawberry   10

更新后的库存应该是什么样的

ProductID  Description  Qty
1          Grape        13
2          Apple        19
3          Pear         11
4          Orange       14
5          Strawberry   13

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

UPDATE INVENTORY
SET Qty = Qty + (SELECT SUM(ShipQty) FROM INBOUND WHERE ProductID = INVENTORY.ProductID)

答案 1 :(得分:0)

尝试以下:

update INVENTORY
set qty = qty + TotalQty
from (
select INBOUND.ProductID, sum(shipqty) as TotalQty
from INBOUND
group by INBOUND.ProductID
) as a
where a.ProductID = INVENTORY.ProductID