连接多列多行的字符串

问题描述 投票:0回答:1

如何在SQL Server中连接多行多列的字符串。

我的桌子是这样的:

     ItemId         AttributeName      AttributeValue
    ----------      -------------      --------------
    1               Website            www.abc.com
    1               Github             github.com/abc
    1               Facebook           facebook.com/abc
    2               Website            www.123.com
    2               Instagram          instagram.com/123

并且所需的输出是:

     ItemId         Weblinks      
    ----------      -------------      
    1               Website: www.abc.com; Github: github.com/abc; Facebook: facebook.com/abc    
    2               Website: www.123.com; Instagram: instagram.com/123

我从其他类似的问题中读到,可能需要XML PATH。请任何人指导我如何实现这一目标?

sql sql-server
1个回答
0
投票

您可以使用FOR XML PATH()

SELECT DISTINCT T.ItemId, STUFF(Weblinks, 1, 1, '') AS Weblinks      
FROM table T CROSS APPLY
     ( SELECT CONCAT(';', T1.AttributeName, ':', T1.AttributeValue)
       FROM table T1 
       WHERE T1.ITEMID = T.ITEMID
       FOR XML PATH('')
     ) T1(Weblinks);
© www.soinside.com 2019 - 2024. All rights reserved.