Agregating a column of text values

Kevin M 136 Reputation points
2021-03-10T20:32:09.247+00:00

Hi!

I'm working in MS Report Builder and trying to create a summary of text values from a column by building them into one string.

In the table example below, I have 3 rows of data with 3 different text values of colors. I want to take all 3 values and put them into row 4 as one string with commas separating them as shown in the example.

76395-table.png

I have tried JOIN but not getting anywhere.

TIA, Kevin

SQL Server Reporting Services
SQL Server Reporting Services
A SQL Server technology that supports the creation, management, and delivery of both traditional, paper-oriented reports and interactive, web-based reports.
3,061 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Joyzhao-MSFT 15,631 Reputation points
    2021-03-11T05:11:19.697+00:00

    Hi @Kevin M ,
    Using TSQL statements will be relatively simple.
    You can refer to the following two methods:
    Method 1:

      SELECT Color = STUFF((  
             SELECT ',' + Color  
                FROM TableName  
                FOR XML PATH('')  
             ), 1, 1, '')  
    

    Method 2:

    SELECT STRING_AGG( ISNULL(Color, ' '), ',') As Color  
       FROM TableName  
    

    Output:
    76507-02.jpg

    Hope this helps.
    Best Regards,
    Joy


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Joyzhao-MSFT 15,631 Reputation points
    2021-03-11T07:05:39.987+00:00

    Hi @Kevin M ,
    You could update the output results you want in the original table, as shown in the following figure:
    Design:
    76648-03.jpg
    Preview:
    76649-04.jpg
    Refer to the following TSQL statement to update the original table:

    IF exists (select * from sysobjects where name='TableName')  
       drop table TableName  
    
    CREATE TABLE TableName(  
           RowNumber     Int IDENTITY(1,1) NOT NULL    
          ,Color VARCHAR(50) NOT NULL  
        );  
      
     INSERT INTO TableName(Color)   
        VALUES ('Red'),  
          ('Yellow'),  
          ('Blue');  
         
      INSERT INTO TableName  
         SELECT Color = STUFF((  
              SELECT ',' + Color  
                 FROM TableName  
                 FOR XML PATH('')  
              ), 1, 1, '')  
      
      SELECT * FROM TableName  
    

    Output:
    76539-05.jpg
    Best Regards,
    Joy


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.