Get the mentioned output by SQL query

You can use below query . String split works on SQL server 2016 and later versions.

 Select * into #temp 
    from #location l 
    join (
    select item,value  from #item
     CROSS APPLY STRING_SPLIT(location_id, ',')
        ) A on l.id=a.value


     select
        item, 
        stuff((
            select ',' + u.city
            from #temp u
            where u.item = A.item
            for xml path('')
        ),1,1,'') as List
    from #temp A
    group 

by item
Drop table #temp

Leave a Comment