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

StackOverflow https://stackoverflow.com/questions/22827948

Question

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?

Was it helpful?

Solution

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 

OTHER TIPS

Use subquery

SELECT Z.EmployeeName,Z.Departments FROM (
   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
) Z
group by Z.EmployeeName, Z.Departments
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top