Sql select query combining row and column values

Hema Ramachandran 176 Reputation points
2021-07-22T08:27:02.92+00:00

My input table table is as follows:
117025-image.png

I need the result as follows:
116989-image.png

Please help.

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,637 questions
{count} votes

Accepted answer
  1. EchoLiu-MSFT 14,581 Reputation points
    2021-07-22T08:40:42.997+00:00

    Hi @Hema Ramachandran ,

    Welcome to the microsoft TSQL Q&A forum!

    Please check:

    CREATE TABLE #test(col1 int,col2 varchar(15),col3 varchar(15))  
    INSERT INTO #test VALUES(1,'EEB','JOL'),(2,'SNF','SNF')  
                            ,(3,'PLY','PLY'),(4,'SBE','SBE')  
     ,(4,'JDA','JDA'),(5,'JEP','JEP')  
     ,(6,'HVE','HVE'),(7,'KMK','PMA')  
     ,(7,'PMA','SDF'),(7,'SBE','SBE')  
      
      
    ;WITH cte  
    as(SELECT col1,col2 FROM #test  
       UNION ALL  
       SELECT col1,col3 FROM #test)  
      
    SELECT * FROM (  
    SELECT col1,  
    (SELECT DISTINCT col2+';' FROM cte  
      WHERE col1=c.col1  
      FOR XML PATH('')) AS col2  
    FROM cte c   
    GROUP BY col1  
    ) t   
    

    Output:
    117008-image.png

    If you have any question, please feel free to let me know.

    Regards
    Echo


    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

0 additional answers

Sort by: Most helpful

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.