Hey all so I am trying to add to (or subtract from) a column of different values based on a separate column in another table. Here is a example of what I am tying to do:
Table 1: (Current Inventory)
ItemName | Quantity
----------|----------
Baseball | 5
Football | 10
Jersey | 3
Table 2: (New Shipment)
ItemName | Quantity
----------|----------
Baseball | 70
Football | 100
Jersey | 50
How can I update my all items in Table 1 (current inventory) by adding Table 2's quantity to them?
1 Answer 1
You can do this using an UPDATE
:
UPDATE inventory i
SET quantity = ( SELECT s.quantity+i.quantity
FROM shipment s
WHERE s.itemname = i.itemname );
or a MERGE
:
MERGE INTO inventory
USING
(
SELECT itemname, quantity
FROM shipment
) ship ON (ship.itemname = inventory.itemname)
WHEN MATCHED THEN UPDATE
SET inventory.quantity = ship.quantity + inventory.quantity;
Example SQL Fiddle here if you want to play.
answered Mar 2, 2015 at 12:43
-
Nice. The first may need adjustments, if the items appear multiple times in
shipment
(or none, so nulls will appear due toSUM
). Something like:SET quantity = quantity + COALESCE( ( SELECT SUM(s.quantity) FROM shipment s WHERE s.itemname = i.itemname ), 0);
ypercubeᵀᴹ– ypercubeᵀᴹ2015年03月11日 09:14:38 +00:00Commented Mar 11, 2015 at 9:14
lang-sql
ItemName
, in both tables?