surfasb
surfasb

Reputation: 968

Not contained in aggregate or having. .

Back to this query again. So I thought I was doing this correctly with a subquery. . .

use Northwind
Select * From (
SELECT FirstName + ' ' + LastName as 'Full Name',
sum(UnitPrice * Quantity) as 'Total Sales',
YEAR(OrderDate) as SalesYear
From Employees e
Join Orders o on o.EmployeeID = e.EmployeeID
join OrderDetails od on od.OrderID = o.OrderID) as subst
Group by 'Full Name', SalesYear  
Order by 'Total Sales' desc

The error I get is the "invalid in the select list because it isn't contained in either an aggregate function or the group by clause. I had it without the subquery earlier and it worked fine . . .

Upvotes: 0

Views: 58

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239764

The aggregate function (e.g. SUM) and the grouping have to be done at the same "level" of the query:

use Northwind
Select 'Full Name',SalesYear,SUM(Sale) as 'Total Sales' From (
    SELECT FirstName + ' ' + LastName as 'Full Name',
    UnitPrice * Quantity as Sale,
    YEAR(OrderDate) as SalesYear
    From Employees e
       Join Orders o on o.EmployeeID = e.EmployeeID
       join OrderDetails od on od.OrderID = o.OrderID) as subst
Group by 'Full Name', SalesYear  
Order by 'Total Sales' desc

Upvotes: 2

Related Questions