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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With