我正在尝试在我的SQL Server数据库中合并这样的内容:
[TicketID], [Person] T0001 Alice T0001 Bob T0002 Catherine T0002 Doug T0003 Elaine
变成这个:
[TicketID], [People] T0001 Alice, Bob T0002 Catherine, Doug T0003 Elaine
我需要在SQL Server和Oracle中都这样做。
我发现GROUP_CONCATMySQL的功能完全可以满足我的需要,但是MySQL并不是这里的选择。
GROUP_CONCAT
编辑: 测试台:
DECLARE @Tickets TABLE ( [TicketID] char(5) NOT NULL, [Person] nvarchar(15) NOT NULL ) INSERT INTO @Tickets VALUES ('T0001', 'Alice'), ('T0001', 'Bob'), ('T0002', 'Catherine'), ('T0002', 'Doug'), ('T0003', 'Elaine') SELECT * FROM @Tickets
这是在SQL Server 2005+中可以使用的解决方案:
SELECT t.TicketID, STUFF(ISNULL((SELECT ', ' + x.Person FROM @Tickets x WHERE x.TicketID = t.TicketID GROUP BY x.Person FOR XML PATH (''), TYPE).value('.','VARCHAR(max)'), ''), 1, 2, '') [No Preceeding Comma], ISNULL((SELECT ', ' + x.Person FROM @Tickets x WHERE x.TicketID = t.TicketID GROUP BY x.Person FOR XML PATH (''), TYPE).value('.','VARCHAR(max)'), '') [Preceeding Comma If Not Empty] FROM @Tickets t GROUP BY t.TicketID
参考: