当前位置: 首页 > 知识库问答 >
问题:

列“*”在select列表中无效,因为它不包含在聚合函数或GROUP BY子句中

司徒志强
2023-03-14

我有一个如下所示的查询

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

但当我执行上面的sql时,出现了一个错误:

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

预期结果:

上面的SQL有什么问题?

共有1个答案

景翰音
2023-03-14

我认为这是因为group by子句中缺少EmployeeID列。子查询中指定的列也应包含在group by子句中。

请尝试:

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 
 类似资料: