在SQL中将行合并为一列

时间:2019-05-28 21:56:48

标签: sql sql-server

我有一个行列表,其中包含名称领导者姓名和经理姓名,但是这些记录是在加入几个表之后出现的

SELECT DISTINCT 
    (leader.name), manager.Name 
FROM 
    ref, leader, orgList, manager, modules 
WHERE 
    leader.id = orgList.leaderCode
    AND orgList.dept = ref.id
    AND orgList.manager = manager.id
    AND orgList.id = modules.orgListId
    AND ref.id = 'xyzzz123'
    AND ref.month = 'august'
    AND modules.year = '2018'

我得到这样的结果

leader_name       manager_name
---------------------------------
 John              Jim
 John              Hiko
 John              Sevu
 John              Celi
 Kerst             Newon
 Kerst             Dollace

但是我实际上想要这样的结果

leader_name       manager_name
------------------------------------
John              Jim;Hiko;Sevu;Celi
Kerst             Newon;Dollace

我尝试了数据透视及其他操作,但仅适用于一张桌子。

1 个答案:

答案 0 :(得分:2)

检查此-

注意:使用标准JOIN代替逗号分隔的JOIN

WITH CTE(leader_name,manager_name)
AS
(
    SELECT DISTINCT 
        (leader.name) leader_name, manager.Name  manager_name
    FROM 
        ref, leader, orgList, manager, modules 
    WHERE 
        leader.id = orgList.leaderCode
        AND orgList.dept = ref.id
        AND orgList.manager = manager.id
        AND orgList.id = modules.orgListId
        AND ref.id = 'xyzzz123'
        AND ref.month = 'august'
        AND modules.year = '2018'
)


SELECT 
leader_name ,
manager_name = 
    STUFF
    (
            (
                SELECT ';' + manager_name 
                FROM CTE B
                WHERE A.leader_name = B.leader_name
                FOR XML PATH ('')), 1, 1, ''
    )
FROM CTE A
GROUP BY leader_name