如何获取逗号分隔的每个部门的员工列表

时间:2017-11-14 07:22:44

标签: sql sql-server-2008

我在下面尝试过使用XML Path但收到错误。

  

将varchar值','转换为数据类型int。

时转换失败

您能否更正以下问题。

SELECT STUFF((SELECT ',' + COUNT(E.EMployeeId) FROM EMployee E WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department) 
            FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'') 

必需的输出

5,7,8,9

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

COUNT()返回integer值,您无法将intvarchar合并。因此,您必须convert将值char

SELECT STUFF((SELECT ',' + CAST(COUNT(E.EMployeeId) AS VARCHAR) FROM EMployee E WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department) 
            FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')

试试这个答案,如果您遇到任何问题,请在评论中提及:

SELECT DISTINCT DepartmentId,
     STUFF(
        (
            SELECT ',' + CAST(COUNT(E.EMployeeId) AS VARCHAR) 
            FROM EMployee E 
            WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department) 
                AND E.DepartmentId=T.DepartmentId
            FOR XML PATH(''), TYPE
            ), 1, 1, '') AS id_list
FROM EMployee as T

尝试使用此部分,以逗号分隔的部门和COUNT()

SELECT STUFF((SELECT ',' + CAST((DepartmentId)AS VARCHAR) 
FROM(
    SELECT DepartmentId,COUNT(EMployeeId) EMployeeId
    FROM EMployee E 
    WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department) 
    GROUP BY DepartmentId
    )E
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'') DepID
    ,STUFF((SELECT ',' + CAST((EMployeeId)AS VARCHAR)
FROM(
    SELECT DepartmentId,COUNT(EMployeeId) EMployeeId
    FROM EMployee E 
    WHERE E.DepartmentId IN(SELECT DepartmentId FROM Department) 
    GROUP BY DepartmentId
    )E
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'')EmpCount