我可以用逗号将多个行分隔成一个列吗?我试图在我的SQLServer数据库中合并这样的内容:[TicketID], [Person]
T0001 Alice
T0001 Bob
T0002 Catherine
T0002 Doug
T0003 Elaine为此:[TicketID], [People]
T0001 Alice, Bob
T0002 Catherine, Doug
T0003 Elaine我需要在SQLServer和Oracle中都这样做。我找到了这个功能GROUP_CONCAT对于MySQL来说,这正是我在这里所需要的,但是MySQL在这里不是一个选项。编辑:试验台: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
3 回答
烙印99
TA贡献1829条经验 获得超13个赞
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 tGROUP BY t.TicketID
largeQ
TA贡献2039条经验 获得超7个赞
select TicketId, GROUP_CONCAT(Person ORDER BY Person SEPARATOR ', ') Peoplefrom tablegroup by TicketId
守着一只汪
TA贡献1872条经验 获得超3个赞
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 @TicketsSelect [TicketID],STUFF((SELECT ',' + Person FROM @Tickets WHERE (TicketID=Result.TicketID) FOR XML PATH ('')),1,1,'') AS BATCHNOLISTFrom @Tickets AS ResultGROUP BY TicketID
添加回答
举报
0/150
提交
取消