I have a complicated query which returns this:
MyID col1 col2 col3
1 A:11
1 A:21
1 A:31
1 C:13
1 C:23
2 B:21
2 B:22
I saved the result set of this query in a temp table #tt
to make things simpler later on.
What I want to achieve is this:
MyID col1 col2 col3
1 A:11__A:21__A:31 C:13__C:23
2 B:21__B:22
But the final query returns this:
MyID col1 col2 col3
1 A:11__A:21__A:31__ ________ ____C:13__C:23
2 __ B:21__B:22 __
This is the query:
select
MyID,
col1= stuff((select N'__' + col1 from #tt where MyID = x.MyID for xml path(''), type ).value(N'.[1]', N'nvarchar(max)'), 1, 2, N'' ),
col2= stuff((select N'__' + col2 from #tt where MyID = x.MyID for xml path(''), type ).value(N'.[1]', N'nvarchar(max)'), 1, 2, N'' ),
col2= stuff((select N'__' + col3 from #tt where MyID = x.MyID for xml path(''), type ).value(N'.[1]', N'nvarchar(max)'), 1, 2, N'' )
from #tt as x
group by MyID
As you can see, there are a lot of underscores being returned. Since I am showing a smaller sample of the data, there will be more unneeded underscores when I ran on entire table. It does appear that I am doing some tiny mistake which I cannot figure out. How can I fix the issue?
If I was using SQL Server 2017 or later, string_agg()
might have helped a lot.