我在SQL中有一个数据表,其中一个人被分配了多个城市。我想成为这些城市的一员。
Name | City
Per 1 | A
Per 1 | B
Per 1 | C
Per 2 | A
Per 2 | B
Per 3 | A
Per 3 | B
Per 3 | C
Per 4 | D
Per 4 | E
Per 5 | A
Per 5 | B
这些城市的地区明智组将如下所示。
Region | City
Reg 1 | A
Reg 1 | B
Reg 1 | C
Reg 2 | A
Reg 2 | B
Reg 3 | D
Reg 3 | E
是否可以在SQL 2014中完成?
答案 0 :(得分:0)
试试这个:
select 'Reg ' + cast(ROW_NUMBER() over (order by (select null)) as varchar(3)) [Region], [Cities] from (
--this query perform concatenation of cities (separated by comma) Name-wise
select distinct replace(replace((select city + ',' from @x where Name = X.Name for xml path('')), '<city>',''),'</city>','') [Cities]
from @x [X]
) a
结果是:
Region Cities
Reg 1 A,B,
Reg 2 A,B,C,
Reg 3 D,E,
我希望这是可以接受的:)