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