将列中的值聚合/连接成单行

时间:2011-06-27 13:12:02

标签: sql-server

我有几千个特许经营权,以及大约3或4个服务组。服务组在一个单独的表中,然后我有第三个表将它们连接在一起。特许经营可以连接到一个或多个服务组。我想要实现的是列出特许经营权,标有“服务类别”的列。然后它将是一个逗号分隔的列表,列出了它们提供的服务。所以现在,这是我的输出:

id  Service Groups     name                    email                address      City         State
1   Cleaning Services  Franchise of LocationX  example@example.com  123 Fake st. Springfield  TheOneTheSimpsonsLiveIn
2   Disaster Services  Franchise of LocationX  example@example.com  123 Fake st. Springfield  TheOneTheSimpsonsLiveIn

我想拥有它,所以它变成了这个:

id  Service Groups                        name                    email                address      City         State
1   Cleaning Services, Disaster Services  Franchise of LocationX  example@example.com  123 Fake st. Springfield  TheOneTheSimpsonsLiveIn

我可以用来做这方面的任何方法/功能的建议或参考将非常感激。谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个

Declare @TempServiceGroups varchar(max)=''
Select COALESCE(@TempServiceGroups,'')+ServiceGroups+',' from MyTable
Select @TempServiceGroups AS ServiceGroups , Name,Email,Address,City,State
from MyTable
相关问题