1

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
3
  • 1
    Please reformat to make it more readable. Commented Nov 13, 2015 at 7:20
  • @MattiasLindberg iam sorry please make me know if my question are not clear. Commented Nov 13, 2015 at 7:25
  • @Vivek.S i'll try.. thank you :) Commented Nov 13, 2015 at 8:18

1 Answer 1

3
 update  products  set stockvolume = stockvolume - diary.minus from 
(SELECT  STOCKDIARY.product,SUM(UNITS) AS MINUS
 FROM STOCKDIARY
 INNER JOIN PRODUCTS
 ON PRODUCTS.ID = STOCKDIARY.PRODUCT
 GROUP BY STOCKDIARY.product) as diary where products.id= diary.product

dont use reserved words as tablenames, column names and etc ... :)

Sign up to request clarification or add additional context in comments.

1 Comment

its solve my proble .. but i must change "stockvolume + diary.minus) because my db already "-" for the stock volume..thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.