I’m not sure what I am doing wrong. This is a sample query from a T-SQL Fundamentals book that I am reading…
SELECT empid, orderdate FROM Sales.Orders
WHERE custid = 71
GROUP BY empid, YEAR(orderdate)
I get the following error:
Msg 8120, Level 16, State 1, Line 1 Column ‘Sales.Orders.orderdate’ is
invalid in the select list because it is not contained in either an
aggregate function or the GROUP BY clause.
What the heck am I doing wrong?…
The
GROUP BYyou provided is working offempidand the year of the orderdate (an INT). But theSELECTis returningempidand a DATETIME data type… Disregarding the data type, the data is different between what is being grouped & presented.You need to use:
…or:
Alternately, SQL Server allows you to reference column aliases in the GROUP BY: