【问题标题】:Column '*' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause列“*”在选择列表中无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中
【发布时间】:2014-05-14 17:02:23
【问题描述】:

我有如下查询

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有什么问题?

【问题讨论】:

    标签: sql sql-server aggregate-functions


    【解决方案1】:

    使用子查询

    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
    

    【讨论】:

      【解决方案2】:

      我认为这是因为 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 
      

      【讨论】:

        猜你喜欢
        • 2014-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 2019-11-01
        相关资源
        最近更新 更多