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

문제

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?

도움이 되었습니까?

해결책

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 

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top