0

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.

jarlh
  • 42,561
  • 8
  • 45
  • 63
Farhan
  • 2,535
  • 4
  • 32
  • 54
  • 1
    Does this answer your question? [Alternative to STRING\_AGG in with SQL](https://stackoverflow.com/questions/59660493/alternative-to-string-agg-in-with-sql) – SMor Sep 23 '20 at 19:29

2 Answers2

0

Filter out the empty or NULL values in your subqueries.

... from #tt where MyID = x.MyID AND col1 IS NOT NULL AND col1 <> '' ...

(And analog for col2 and col3.)

sticky bit
  • 36,626
  • 12
  • 31
  • 42
0

Is this where you're trying to get to?

SELECT
    MyID,
    col1 = ISNULL(STUFF((SELECT N'__' + NULLIF(col1, '') FROM #tt WHERE MyID = x.MyID FOR XML PATH(''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 2, N''), ''),
    col2 = ISNULL(STUFF((SELECT N'__' + NULLIF(col2, '') FROM #tt WHERE MyID = x.MyID FOR XML PATH(''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 2, N''), ''),
    col2 = ISNULL(STUFF((SELECT N'__' + NULLIF(col3, '') FROM #tt WHERE MyID = x.MyID FOR XML PATH(''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 2, N''), '')
FROM
    #tt x
GROUP BY
    MyID;
Jason A. Long
  • 4,382
  • 1
  • 12
  • 17