简体   繁体   中英

How to concatenate column data in SQL Server 2016?

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.

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 .)

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM