Question

I learning SQL, using Northwind example database and I'm completely stuck on very simple problem: I want to list all products name in one column and total quantities sold for each product in second column. First, I did this:

select p.ProductId
    ,sum(od.Quantity) as TotalQuantity 
from Products p  
join [Order Details] od 
    on p.ProductId=od.Productid
group by p.ProductId

and that's ok - I have product id's and total quantities, but when I try something like this:

select p.productid
    ,p.ProductName
    , sum(od.quantity) as TotalQuantity
from products p  
join [Order details] od 
    on p.productid=od.productid
group by p.productid

I get error:

Msg 8120, Level 16, State 1, Line 1
Column 'products.ProductName' is invalid in the select list because 
it is not contained in either an aggregate function or the GROUP BY clause.`
Was it helpful?

Solution

When you use aggregate functions (like sum) you have to group by every other field in select

You have to modify your query as follows

select p.productid, p.ProductName, sum(od.quantity) as TotalQuantity from
products p  join [Order details] od on p.productid=od.productid
group by p.productid, p.ProductName

OTHER TIPS

Given that you will never going to get different ProductNames for a single ProductId, you can also try:

select p.productid
, min(p.ProductName) as ProductName
, sum(od.quantity) as TotalQuantity
from products p  
join [Order details] od 
    on p.productid=od.productid
group by p.productid
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top