Update Query With SUM

Johnathan Simpson 586 Reputation points
2020-10-26T15:50:23.113+00:00

How would I update my table using this update statement? Note - this is sample DDL only, actual table structure does not have a calculated field like this

Declare @orderinfo Table
(
    ordernumber varchar(10)
   ,ordersalesperson varchar(100)
   ,orderfromstore varchar(50)
   ,orderTotal decimal(16,4)
)

Declare @orderline Table
(
  ordernumber varchar(10)
  ,orderitemquantity int
  ,orderitemprice decimal(16,4)
)

Insert Into @orderinfo (ordernumber, ordersalesperson, orderfromstore) VALUES
('ABC123', 'Sales Person A', 'Store 1')

Insert Into @orderline Values
('ABC123', '2', '3.75'), ('ABC123', '4', '5.25'), ('ABC123', '2', '7.48')

UPDATE oi
SET orderTotal = SUM(ol.orderitemquantity * ol.orderitemprice)
From @orderinfo oi
Join @orderline ol
On oi.ordernumber = ol.ordernumber
Developer technologies | Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2020-10-26T16:22:50.577+00:00

    Try one of possibilities:

    update oi
    set ordertotal = (select ISNULL(SUM(orderitemquantity * orderitemprice), 0) from @orderline where ordernumber = oi.ordernumber) 
    from @orderinfo oi
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. scott_morris-ga 16 Reputation points
    2020-10-26T16:22:58.43+00:00

    For future reference, you should include the complete error message you encountered (but after having searched the internet for it). It is a common error and there are many discussions you can find which suggest various approaches. Have you considered a view (materialized or not) that will always have the correct value? Or perhaps a trigger? Below is one example:

    with cte as (select ol.ordernumber, 
         sum(ol.orderitemquantity * ol.orderitemprice) as totalord 
         from  @orderline as ol group by ol.ordernumber )
     update oi set orderTotal = cte.totalord
     from @orderinfo as oi inner join cte 
     on oi.ordernumber = cte.ordernumber; 
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.