Search code examples
sqlsql-serverjoinreport

SQL combining data from two rows into a single row when they share a common identifier


For a report I'm working on I need to combine data from rows in a specific column based on the data they share in a separate column. All data is from the same table:

      ID       |        Name        | 
    10000             Jane Doe            
    10000             John Smith
    50000             Jack Bauer
    50000             Jon Snow
    90000             Jack Bauer

I need to somehow combine the Name row together when they share a common ID value:

      ID       |        Name        | 
    10000             Jane Doe, John Smith            
    50000             Jack Bauer, Jon Snow
    90000             Jack Bauer

The ID is not the primary key for this table but it's what I need as the unique value on the report.

I'm mostly self taught and admittedly lacking a perfect SQL vocabulary. I can't quite think of how to articulate the code in order to do this. Any help with the logic would be immensely appreciated!

Dave


Solution

  • Test Data

    DECLARE @TABLE TABLE (ID INT, Name VARCHAR(50))
    INSERT INTO @TABLE VALUES
    (10000,'Jane Doe'),            
    (10000,'John Smith'),
    (50000,'Jack Bauer'),
    (50000,'Jon Snow'),
    (90000,'Jack Bauer')
    

    Query

    SELECT t.ID
          ,STUFF((SELECT ', ' + Name
                  FROM @Table
                  WHERE ID = t.ID 
                  FOR XML PATH(''),TYPE)
                  .value('.','NVARCHAR(MAX)'),1,2,'') AS Names
    FROM @TABLE t
    GROUP BY t.ID
    

    Result Set

    ╔═══════╦══════════════════════╗
    ║  ID   ║        Names         ║
    ╠═══════╬══════════════════════╣
    ║ 10000 ║ Jane Doe, John Smith ║
    ║ 50000 ║ Jack Bauer, Jon Snow ║
    ║ 90000 ║ Jack Bauer           ║
    ╚═══════╩══════════════════════╝