Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column '*' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

I have a query like below

select a.EmployeeName, 

STUFF(( SELECT ',' + camTable.DepartmentName AS [text()]
                        FROM EmpoyeeDepartment subTable
                left join DepartmentTable camTable on subTable.DepartmentID = camTable.DepartmentID 
                        WHERE
                        subTable.EmployeeID = a.EmployeeID
                        FOR XML PATH('')
                        ), 1, 1, '' )
            AS Departments
from 
EmployeeTable a
where a.EmployeeID = 144025
group by EmployeeName, Departments

But when I execute the above sql, there's an error :

Column 'EmployeeTable.EmployeeID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Expected result:

enter image description here

What's wrong with the above sql?

like image 326
User2012384 Avatar asked Mar 21 '23 00:03

User2012384


1 Answers

I think its because of EmployeeID column missing in group by clause. Columns specified in sub-query also should be included in group by clause.

Please Try:

select a.EmployeeName, 

STUFF(( SELECT ',' + camTable.DepartmentName AS [text()]
                        FROM EmpoyeeDepartment subTable
                left join DepartmentTable camTable on subTable.DepartmentID = camTable.DepartmentID 
                        WHERE
                        subTable.EmployeeID = a.EmployeeID
                        FOR XML PATH('')
                        ), 1, 1, '' )
            AS Departments
from 
EmployeeTable a
where a.EmployeeID = 144025
group by EmployeeID, EmployeeName, Departments 
like image 177
TechDo Avatar answered Mar 22 '23 19:03

TechDo