我有以下数据
Name Description
a-c-v ad-cfd-gft-anonmymous data-typegf
t-r tsjdg-dgdt-testing the data-check the test-type
f test-1234-tlelephone
我需要sql查询,它会将结果显示为
ad-cfd-gft
tsjdg-dgdt
test
根据名称中的冒号,我应该从描述中得到结果。 我正在使用sql server 2008,请你帮忙 编辑了我的数据
答案 0 :(得分:0)
select name
,cast (Description.query('/r/e[position() <= sql:column("tokens_num")]/text()') as varchar(max)) as Description
from (select name
,len(name) - len(replace(name,'-','')) + case when name = '' then 0 else 1 end as tokens_num
,cast ('<r><e>' + replace(Description,'-','</e><e>-') + '</e></r>' as xml) as Description
from t
) t
+-------+-------------+
| name | Description |
+-------+-------------+
| a-c-v | ad-cfd-gft |
+-------+-------------+
| t-r | tsjdg-dgdt |
+-------+-------------+
| f | test |
+-------+-------------+
演示(更容易关注数据样本)
declare @t table (Name varchar(100),Description varchar(100))
insert into @t values
('' ,'It''s-a-show-about-nothing')
,('Sting' ,'Englishman-In-New-York')
,('Paul-Simon' ,'The-Sound-Of-Silence')
,('Andrew-Lloyd-Webber' ,'The-Phantom-Of-The-Opera')
select name
,name_tokens_num
,Description as original_Description
,cast (Description_xml.query('/r/e[position() <= sql:column("name_tokens_num")]/text()') as varchar(max)) as new_Description
from (select name
,Description
,len(name) - len(replace(name,'-','')) + case when name='' then 0 else 1 end as name_tokens_num
,cast ('<r><e>' + replace(Description,'-','</e><e>-') + '</e></r>' as xml) as Description_xml
from @t
) t
+---------------------+-----------------+--------------------------+-----------------+
| name | name_tokens_num | original_Description | new_Description |
+---------------------+-----------------+--------------------------+-----------------+
| | 0 | It's-a-show-about-nothing| |
+---------------------+-----------------+--------------------------+-----------------+
| Sting | 1 | Englishman-In-New-York | Englishman |
+---------------------+-----------------+--------------------------+-----------------+
| Paul-Simon | 2 | The-Sound-Of-Silence | The-Sound |
+---------------------+-----------------+--------------------------+-----------------+
| Andrew-Lloyd-Webber | 3 | The-Phantom-Of-The-Opera | The-Phantom-Of |
+---------------------+-----------------+--------------------------+-----------------+