0

I have one table that contains many rows, i was hoping there is a way to update a Total cost column in this table calculated from the sum of another Table.

is it possible to do something along the lines of this:

UPDATE [PO] set TotalCost=(Select sum(Cost) from [PO-Lines] where PO=Update.PO) 

this is so i don't have to create a loop

7
  • What database are you using? SQL Server? MySQL? Or something else? Commented Jul 31, 2014 at 2:50
  • 1
    Square brackets around names suggests Sql Server, since MySQL uses backticks and Oracle uses doublequotes. Commented Jul 31, 2014 at 2:51
  • @Barmar Fair enough. It'd still be nice for the OP to tag it, though. Commented Jul 31, 2014 at 2:52
  • update PO set totalCost = sum(POLines.cost) FROM PO inner join POLines ON PO.id = POLines.id this should be the something that you looking for Commented Jul 31, 2014 at 2:54
  • i'm getting the following error: An aggregate may not appear in the set list of an UPDATE statement. Commented Jul 31, 2014 at 2:57

1 Answer 1

1

I don't know SQL-Server, so I'm extrapolating from MySQL and hoping I get the syntax right. You can do it either with a JOIN:

UPDATE t1
SET t1.TotalCost = t2.Total
FROM [PO] AS t1
JOIN (SELECT POId, SUM(Cost) Total
      FROM [POLines]
      GROUP BY POId) AS t2
ON t1.ID = t2.POId

or a correlated subquery:

UPDATE [PO]
SET TotalCost = (SELECT SUM(Cost) FROM [PO-Lines] WHERE [PO-Lines].POId = [PO].ID)
Sign up to request clarification or add additional context in comments.

6 Comments

I tried this in SQLFiddle and the first one doesn't work. You can't join a query like that. I've never shared a SQL Fiddle before, so I hope this works, but this is it. Just in case I missed something silly.
The second one is spot on, though.
I just linked to a question as a possible duplicate, it shows how to use JOIN in an UPDATE in SQL-Server. I'll see if I can rewrite my answer according to that.
thanks heaps this is what i was after, the 2nd one works
@Barmar sounds good. Although that doesn't address the aggregate matter, which is what makes this particularly difficult. You might be able to do it with a CTE, but I'm far from skilled with those. I think standard practice in SQL, at least from what I'd do, is just to have the subquery as in your second example. It's definitely just as readable and efficient as any other solution, in any event.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.