Select Distinct State, (Select Stuff((Select char(10) + CityFrom #tempCityStateWhere State = t.StateFOR Xml Path('')),1,1,'')) AS CitiesFrom #tempCityState t
Select Distinct State, (Select Stuff((Select '' + CityFrom #tempCityStateWhere State = t.StateFOR Xml Path(''),TYPE).value('.','VARCHAR(1000)'),1,1,'')) AS CitiesFrom #tempCityState t
Create TABLE #tempCityState (State Varchar(5), City Varchar(50))Insert Into #tempCityStateSelect 'CO', 'Denver' UnionSelect 'CO', 'Teluride' UnionSelect 'CO', 'Vail' UnionSelect 'CO', 'Aspen' UnionSelect 'CA', 'Los Anggeles' UnionSelect 'CA', 'Hanford' UnionSelect 'CA', 'Fremont' UnionSelect 'AK', 'Wynne' UnionSelect 'AK', 'Nashville';--Select Distinct State, (Select Stuff((Select ',' + City--From #tempCityState--Where State = t.State--FOR Xml Path('')),1,1,'')) AS Cities--From #tempCityState t;with States as (select distinct Statefrom #tempCityState)select State, stuff((select '' + City + char(13) + char(10) from #tempCityState tcs where tcs.State = States.State order by tcs.City for xml path(''),TYPE).value('.','varchar(max)'),1,0,'') as Citiesfrom States;Drop table #tempCityState