SQL用分隔符分割的VALUE 怎么从另一张表取得text
表A
ID VALUES
1 a,b,c
2 c,d
表B
ID text value
1 一 a
2 二 b
3 五 c
4 六 d
想写SQL 得
字段A 字段B
a,b,c 一,二,五
c,d 五,六
请问怎么写
------解决方案--------------------
with tb(ID,[VALUES])as(
select 1,'a,b,c' union
select 2,'c,d')
,tc(ID,text,value)as(
select 1,'一','a' union
select 2,'二','b' union
select 3,'五','c' union
select 4,'六','d')
,td as(
select [values],tb.ID,text from tb,master..spt_values,tc
where type='p' and SUBSTRING(','+[values],number,1)=','
and SUBSTRING([values],number,1)=tc.value
)
select distinct [values],
text=stuff((select ','+text from td where a.ID=ID for xml path('')),1,1,'') from td a
------解决方案--------------------with A (ID,[VALUES]) as
(
select 1,'a,b,c' union all
select 2,'c,d'
)
,B (ID,[text],[value]) as
(
select 1,'一','a' union all
select 2,'二','b' union all
select 3,'五','c' union all
select 4,'六','d'
)
,c as
(
select b.*,a.[values]
from b cross join a
where charindex(b.[value],a.[values])>0
)
SELECT d.[values],[text]=stuff
(
(select ','+RTRIM([text]) as [text()]
from c e where d.[values]=e.[values]
for xml path('')
),1,1,'') FROM c d group by d.[values]