将许多行连接成单个文本字符串

时间:2013-10-01 09:28:14

标签: sql sql-server tsql

我正在尝试将多个名称连接到一个列中,但是我无法到达那里。

DECLARE @Names VARCHAR(8000) 

SELECT 
    p.Pato_Id
    @Names = COALESCE(@Names + ', ', '') + e.First_Name + ' ' + e.Last_Name

FROM 
    Patos p

LEFT JOIN 
    Pato_Owners po
ON
    po.Pato_Id = p.Pato_Id
LEFT JOIN 
    Person e
ON
    po.Owner_Id = e.Person_Id

如何做到这一点?

修改

当我正常选择时,我

PatoID First  Last 
0      John   Wort
0      Dan    Mass
1      Till   Bos
2      Wrap   Sim
2      Port   Lock

我想要的是:

PatoID Names
0      John Wort, Dan Mass
1      Till Bos
2      Wrap Sim, Port Lock

3 个答案:

答案 0 :(得分:0)

我想你想要这个,

WITH Sales_CTE (Pato_Id, First, Last)
AS
(
Select p.Pato_Id , e.First , e.Last
FROM 
    Patos p
LEFT JOIN 
    Pato_Owners po
ON
    po.Pato_Id = p.Pato_Id
LEFT JOIN 
    Person e
ON
    po.Owner_Id = e.Person_Id
)
SELECT Pato_Id,  
Substring((Select ',' + ISNULL(First,'') +  ISNULL(Last,'') From Sales_CTE B Where B.Pato_Id=A.Pato_Id For XML Path('')),2,8000) As names  
 from Sales_CTE A group by Pato_Id;

答案 1 :(得分:0)

您已离开联接,表示您可以使用空名称。这将重置发生的名称值。

;with cte as
(
SELECT 
    p.Pato_Id,
    coalesce(e.First_Name, '') + coalesce(' ' + e.Last_Name, '') Name
FROM 
    Patos p

LEFT JOIN 
    Pato_Owners po
ON
    po.Pato_Id = p.Pato_Id
LEFT JOIN 
    Person e
ON
    po.Owner_Id = e.Person_Id
)

select t.Pato_id
    ,STUFF(( 
        select ',' + [name] 
        from cte t1 
        where t1.Pato_Id = t.Pato_Id
        for xml path(''), type 
    ).value('.', 'varchar(max)'), 1, 1, '') [Names] 
from cte t 
group by t.Pato_id 

答案 2 :(得分:0)

试试这个,

DECLARE @Names VARCHAR(8000) 

SELECT 
p.Pato_Id,
'ServerName' = COALESCE(@Names + ', ', '') + e.First_Name + ' ' + e.Last_Name

FROM 
Patos p

LEFT JOIN 
Pato_Owners po
ON
po.Pato_Id = p.Pato_Id
LEFT JOIN 
Person e
ON
po.Owner_Id = e.Person_Id