I would like to aggregate results of a column into a single row using MS SQL.
I have create a sql fiddle which showcases the issue:
http://sqlfiddle.com/#!3/384d5/2
Basically I would like all 'Tag' results on the same line, grouped by the different Tags
So in the example results above, I would expect the results to be like so:
Id | Tag | OptionText
1 | IsMobile | Yes
1 | Mission | I am buying this, I am using this
The closest I have got is by using a STUFF function but I can't seem to get it correctly as it outputs all the OptionText values on each row:
select Id, Tag, STUFF(CAST((
SELECT [text()] = ', ' + [OptionText]
FROM testing
FOR XML PATH(''), TYPE) AS
VARCHAR(max)), 1, 2, '') OptionText
from testing
group by Id, Tag
Here are the results for that query: http://sqlfiddle.com/#!3/384d5/5
Best Answer
You need to restrict your sub-query to look for the specific tags of the outer query.
I have aliased your outer table
t1
and inner tablet2
.