I want to ask about SUM and then UPDATE it in Postgresql DB.
In my case I want to sum (units) in stockdiary table and then do the deduction/subtract with table products (stockvolume).
I was able to sum the units in stockdiary table:
SELECT NAME,SUM(UNITS) AS MINUS
FROM STOCKDIARY
INNER JOIN PRODUCTS
ON PRODUCTS.ID = STOCKDIARY.PRODUCT
GROUP BY NAME
result =>
name || minus
USB CABLE 1M || -8
USB CHARGER || -3
then the problem is how to subtract minus and stockvolume and update it back to the products table?
stockdiary table
id(pk),datenew,product,units,price
products table
name,id(pk),pricebuy,pricesell,stockvolume
@Vivek.S thanks it works.
UPDATE products
SET stockvolume = sub.minus
FROM (SELECT
SUM(UNITS) AS MINUS,PRODUCTS.ID
FROM STOCKDIARY
INNER JOIN PRODUCTS ON PRODUCTS.ID = STOCKDIARY.PRODUCT
GROUP BY NAME) sub
WHERE sub.productid = products.productid