嗨我有两张桌子,一张有县信息 和其他人有RowData
国家/地区表格似乎
Country_ID Region_ID Country_Name Abbreviation Priority
----------- ----------- ------------------------- ------------ -----------
1 1 United States USA 1
2 1 US USA 1
3 1 Canada CA 2
4 2 United Kingdom UK 1
5 2 Germany DE 1
6 2 France FR 1
7 2 Italy IT 1
8 2 Spain ES 1
9 2 The Netherlands NL 1
10 2 Poland PL 2
11 2 Russia RU 2
和RowData就像
Tr_ID Countrys
----------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
729541 Germany,United Kingdom
729553 Italy,Poland,Russia,Spain
729580 Austria,Finland,France,Germany,Ireland,Italy,Poland,Portugal,Romania,Russia,Slovakia,Spain,Sweden,Switzerland,The Netherlands,United Kingdom
729726 Italy,Spain,United Kingdom
729737 Austria,United Kingdom
我想根据县表中给出的优先顺序重新排列县名
优先级1县应该是第一个扩展国家,然后重复逗号 请帮帮我
由于
答案 0 :(得分:2)
MS SQL Server 2008架构设置:
create table Country
(
Country_ID int,
Region_ID int,
Country_Name varchar(25),
Abbreviation varchar(5),
Priority int
);
insert into Country values
(1 , 1, 'United States', 'USA', 1),
(2 , 1, 'US', 'USA', 1),
(3 , 1, 'Canada', 'CA ', 2),
(4 , 2, 'United Kingdom', 'UK ', 1),
(5 , 2, 'Germany', 'DE ', 1),
(6 , 2, 'France', 'FR ', 1),
(7 , 2, 'Italy', 'IT ', 1),
(8 , 2, 'Spain', 'ES ', 1),
(9 , 2, 'The Netherlands', 'NL ', 1),
(10, 2, 'Poland', 'PL ', 2),
(11, 2, 'Russia', 'RU ', 2)
create table RowData
(
Tr_ID int,
Countrys varchar(200)
)
insert into RowData values
(729541, 'Germany,United Kingdom'),
(729553, 'Italy,Poland,Russia,Spain'),
(729580, 'Austria,Finland,France,Germany,Ireland,Italy,Poland,Portugal,Romania,Russia,Slovakia,Spain,Sweden,Switzerland,The Netherlands,United Kingdom'),
(729726, 'Italy,Spain,United Kingdom'),
(729737, 'Austria,United Kingdom')
查询1 :
select R.Tr_ID,
(
select ','+C.Country_Name
from Country as C
where ','+R.Countrys+',' like '%,'+C.Country_Name+',%'
order by C.Priority
for xml path(''), type
).value('substring(text()[1], 2)', 'varchar(200)') as Countrys
from RowData as R
<强> Results 强>:
| TR_ID | COUNTRYS |
------------------------------------------------------------------------------------
| 729541 | United Kingdom,Germany |
| 729553 | Italy,Spain,Poland,Russia |
| 729580 | United Kingdom,Germany,France,Italy,Spain,The Netherlands,Poland,Russia |
| 729726 | United Kingdom,Italy,Spain |
| 729737 | United Kingdom |