all. I've just discovered the stuff function in SQL Server, and I'm having difficulty using it the correct way. As you can see, it just lists all the teams out for each row. I've created a sample set of data to better understand my bigger set of data I'm working with.
DECLARE @SportsSurvey table(surveyid int , persID int, city varchar(20),favteam varchar(20))
INSERT @SportsSurvey (surveyid, persID, city, favteam) values
('1234','1','Atlanta','Hawks')
,('2345','3','Dallas', 'Cowboys')
,('3456','4','NYC', 'Nets')
,('4567','1','Atlanta', 'Falcons')
,('5678','5','LA', 'Lakers')
,('6789','7','LA', 'Dodgers')
,('7890','6','Chicago', 'Bears')
,('1234','1','Atlanta', 'Braves')
,('7890','6','Chicago','Cubs')
,('7890','6','Chicago','Bulls')
select
distinct surveyid, persid, city,
stuff((
select (', ' + s.favteam)
from @SportsSurvey s
where s.favteam = favteam
--group by surveyid
order by s.favteam
for xml path('')
),1,1,'') as teams
from @SportsSurvey
/***********************************************/
/***********************************************/
DECLARE @SportsSurvey2 table(surveyid int , persID int, city varchar(20),favteam varchar(100))
INSERT @SportsSurvey2 (surveyid, persID, city, favteam) values
('1234','1','Atlanta','Braves, Hawks')
,('4567','1','Atlanta','Falcons')
,('2345','3','Dallas','Cowboys')
,('3456','4','NYC','Nets')
,('5678','5','LA','Lakers')
,('6789','7','LA','Dodgers')
,('7890','6','Chicago','Bears, Bulls, Cubs')
select *
from @SportsSurvey2
I've also provided the output I'd like to see. Can someone steer me in the right direction? Using SQL Server Management Studio version 15.0
Thank you!