We will be using the table ‘[HR].[Employees]’ from TSQL2012 database.
The error as described in the Title of the post :
"Msg 8120, Level 16, State 1, Line 1 Column 'HR.Employees.lastname' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
The error occured when I executed the following query :
select min(empid) as minimum,lastname from [HR].[Employees]
The reason for the error is : We are missing the group by clause at the end .When we are using an aggregate function along with other columns in the select clause we must use the group by clause .
select min(empid) as minimum,lastname from [HR].[Employees] group by lastname
If you are using more than one column in the select clause while using the aggregate function , then it is necessary to include all the columns in the group by clause except the column on which the aggregate function is applied. For instance : if you use execute the below query , it will throw the same error:
select min(empid) as minimum,lastname,firstname from [HR].[Employees] group by lastname
So , we must include the firstname column as well to successfully execute it as below :
select min(empid) as minimum,lastname,firstname from [HR].[Employees] group by lastname,firstname



