下面是我的代码
Select FromCity, TicketID
From #Main
下面是结果
FromCity TicketID
London Ticket4321
Miami Ticket4321
Singapore Ticket4321
Sydney Ticket1234
我不能使用枢轴,因为我不知道城市的所有名称。 我需要我的结果看起来像这样。
TicketID FromCities
Ticket4321 London/Miami/Singapore
Ticket1234 Sydney
答案 0 :(得分:1)
您可以使用
而不是使用数据透视CREATE TABLE Table1
([FromCity] varchar(9), [Ticket] varchar(10))
;
INSERT INTO Table1
([FromCity], [Ticket])
VALUES
('London', 'Ticket4321'),
('Miami', 'Ticket4321'),
('Singapore', 'Ticket4321'),
('Sydney', 'Ticket1234')
select
Ticket,
stuff((
select distinct '/' + t.[FromCity ]
from Table1 t
where t.Ticket = t1.Ticket
for xml path('')
),1,1,'') as name_csv
from Table1 t1
group by Ticket
输出
TicketID FromCities
Ticket4321 London/Miami/Singapore
Ticket1234 Sydney