SQL: SUM in the middle of a SELECT query fails

Multi tool use
SQL: SUM in the middle of a SELECT query fails
I have the following tables:
Invoice
InvoiceLine
I want to have the following: The company name and total amount of invoice with ID 1760.
I use the following query:
SELECT i.*, sum(il.amount) as 'Total'
FROM invoice i JOIN invoiceLine il on i.invoiceID = il.InvoiceID
WHERE i.InvoiceID = 1760
I get this as error:
Column 'invoice.invoiceID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Why is the error returned and why does it want me to use a GROUP BY clause while i'm only expecting one row to be returned? Would I be obligated to do this in 2 queries?
doesnt solve it, i have the exact same if i use
i.*, SUM(il.amount)
– user3127554
Jul 2 at 17:14
i.*, SUM(il.amount)
you use same case letter as in the table columns fields , you done mistakes in full query , please check it.
– Mohit Kumar
Jul 2 at 17:18
3 Answers
3
You will need a GROUP BY for each column that you are not aggregating
Try this:
SELECT i.invoiceID, i.companyName, sum(il.amount) as 'Total'
FROM invoice i JOIN invoiceLine il on i.invoiceID = il.InvoiceID
WHERE i.InvoiceID = 1760
GROUP BY i.invoiceID, i.companyName
You need to specify columns to group by when performing aggregate functions.
SELECT i.InvoiceID,i.CompanyName, sum(il.amount) as 'Total'
FROM invoice i JOIN invoiceLine il on i.invoiceID = il.InvoiceID
WHERE i.InvoiceID = 1760
group by i.InvoiceID,i.CompanyName
You can use a correlated subquery:
SELECT i.*,
(SELCT sum(il.amount)
FROM invoiceLine il
WHERE i.invoiceID = il.InvoiceID
) as Total
FROM invoice i
WHERE i.InvoiceID = 1760;
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
change this i.invoiceID to i.InvoiceID capital I. and let me know what happens ?
– Mohit Kumar
Jul 2 at 17:12