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

♀尐吖头ヾ 提交于 2019-12-08 04:11:19

问题


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


回答1:


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           ║
╚═══════╩══════════════════════╝


来源:https://stackoverflow.com/questions/23525377/sql-combining-data-from-two-rows-into-a-single-row-when-they-share-a-common-iden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!