我想询问SUM然后在Postgresql DB中更新它。
在我的情况下,我想在stockdiary表中求和(单位),然后用表产品(stockvolume)进行扣除/减法。
我能够在库存表中对单位进行求和:
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,产品,单位,价格
产品表
名称,ID(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
答案 0 :(得分: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
不要使用保留字作为表名,列名等......:)