简体   繁体   中英

How to update the single row twice. Second update should take the updated value from 1st update

I have two tables tblProducts and temptable. temptable contains the details of sold products stock quantity. I want to update sold quantity of products in tblproduct. My problem is temp table will have multiple records for same product and when I update it using join it update on the old value instead of new value.

tblProduct         tempTable
==============     ==========
ProductId            Id
Name                 ProductId
StockQuantity        SoldQuantity
                     OrderType

--------------
tblProduct
--------------
ProductId     Name         TotalSoldQuantity
1          Product1           10    
2          Product2           20

-------------
tempTable
-------------
Id      ProductId   SoldQuantity  OrderType
1          1             5           1
2          1             5           2

I have written below query :

 UPDATE P SET P.TotalSoldQuantity = P.TotalSoldQuantity + T.SoldQuantity 
 FROM tempTable T JOIN tblProduct P ON P.ProductId = T.ProductId

This query update the product1's TotalSoldQuantity to 15 instead of 20. It should update one by one after taking the previous records updated value.

Please help.

You need to aggregate SoldQuantity first to get total sold and then update:

WITH TotalAgg AS
(SELECT T.ProductId, SUM(T.SoldQuantity) AS TSQA FROM tempTable AS T GROUP BY T.ProductId)
UPDATE P SET P.TotalSoldQuantity = P.TotalSoldQuantity + T.TSQA 
FROM TotalAgg T JOIN tblProduct P ON P.ProductId = T.ProductId

I would write it like this, avoiding the non-standard UPDATE ... FROM syntax, and providing a simple pattern for examining the changes before applying them:

with q as
(
  select p.ProductId, 
         p.TotalSoldQuantity, 
         AdditionalSoldQuantity = (select sum(SoldQuantity) from tempTable where productId = p.ProductId) 
  from tblProduct p
)
--select * from q
update q set TotalSoldQuantity = TotalSoldQuantity + AdditionalSoldQuantity 

You need to aggregate your quantitys per ProductId in your temp table and join that to Products.

 UPDATE P 
 SET P.TotalSoldQuantity = P.TotalSoldQuantity + T.SoldQuantity 
 FROM 
    (SELECT ProductId, SUM(TotalSoldQuantity) FROM tempTable GROUP BY ProductId) T JOIN 
    tblProduct P ON P.ProductId = T.ProductId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM