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

StackOverflow https://stackoverflow.com/questions/23525377

  •  17-07-2023
  •  | 
  •  

سؤال

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

هل كانت مفيدة؟

المحلول

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           ║
╚═══════╩══════════════════════╝
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top