2015-11-13 57 views
1

我想問一下SUM,然後在Postgresql DB中更新它。
在我的情況下,我想總結(單位)在stockdary表中,然後做與表產品(stockvolume)的扣除/減去。

我能總結在表stockdiary單位:Postgresql SUM和UPDATE

 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 

那麼問題是如何減去減去stockvolume和更新回到產品表?

stockdiary表
ID(PK),datenew,產品,單位價格

產品表
姓名,身份證(PK),pricebuy,pricesell,stockvolume

@感謝Vivek.S它作品。

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 
+1

請重新格式化,以使其更具可讀性。 –

+0

@MattiasLindberg iam對不起,如果我的問題不清楚,請讓我知道。 – irebmy

+0

@ Vivek.S我會盡力..謝謝你:) – irebmy

回答

0
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 

不使用保留字作爲表名,字段名等.. :)

+0

它解決我的問題..但我必須改變「stockvolume + diary.minus),因爲我的分貝已經」 - 「的股票量...感謝你 – irebmy