0

I need to update newly added column(store the sum of all items of the invoice) with result from subquery which generates more than one rows. I added new column to Invoice table.

ALTER TABLE Invoice
ADD ItemsSum int NULL

I tried following query but it gave error because of multiple results

UPDATE Invoice
SET ItemsSum = (SELECT SUM(Amount)
               FROM InvoiceItem it
               INNER JOIN Invoice i ON it.InvoiceID = i.ID
               GROUP BY i.ID)

How to achieve this correctly in SQL Server?

3 Answers 3

2

You can use correlated subquery :

UPDATE Invoice
     SET ItemsSum = (SELECT SUM(it.Amount) 
                     FROM InvoiceItem it 
                     WHERE it.InvoiceID = Invoice.ID
                    );

ItemsSum will be invalid if underlying invoice amount will be change.

Sign up to request clarification or add additional context in comments.

Comments

0

correlated is :

UPDATE Invoice
     SET ItemsSum = (SELECT SUM(invc.Amount) 
                     FROM InvoiceItem invc 
                     WHERE invc.InvoiceID = Invoice.ID
                     GROUP BY Invoice.ID;
                    );

Comments

0

Yogesh's answer is correct, but if you like, you can also do this using an explicit aggregation:

UPDATE i
    SET ItemsSum = ii.sumAmount
FROM Invoice i LEFT JOIN
     (SELECT ii.InvoiceID, SUM(Amount) as sumAmount
      FROM InvoiceItem it
      GROUP BY ii.InvoiceID
     ) ii
     ON ii.InvoiceID = i.ID

Comments

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.