简体   繁体   中英

Aggregate/concatenate values from a column into a single row

I have a couple thousand franchises, and about 3 or 4 service groups. The service groups are in a separate table, then i have third table joining them together. A franchise may be connected to 1 or many service groups. What I am trying to achieve is listing out the franchises, with a column labeled "Service Categories". It would then be a comma separated list of which services they provide. So right now, here's my output:

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

I would like to have it so it becomes this:

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

Any suggestions or references of methods/functions I can use to do this would be greately appreciated. Thanks!

try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM