当前位置: 代码迷 >> Sql Server >> 列转换的sql 多谢
  详细解决方案

列转换的sql 多谢

热度:74   发布时间:2016-04-24 09:05:56.0
求一个列转换的sql 谢谢
create table #base(fid varchar(4) not null,fname varchar(16) null)
insert into #base (fid,fname) values ('1002','粉尘')
insert into #base (fid,fname) values ('1007','燥音')

select* from #base
create table #record(sid int not null,fid varchar(16) null)

insert into #record(sid,fid) values(1,'1002')
insert into #record(sid,fid) values(2,'1007')
insert into #record(sid,fid) values(3,'1002/1007')

select * from #record




drop table #record
drop table #base

得到以下结果:
1 1002
2 1007
3 1002/1007


我希望得到以下结果
1 粉尘
2 燥音
3 粉尘/燥音

------解决思路----------------------
SELECT T1.sid
,STUFF((SELECT'/'+fname FROM #base T2
WHERE '/'+T1.fid+'/'LIKE'%/'+T2.fid+'/%'
FOR XML PATH(''))
,1,1,'')
FROM #record T1

------解决思路----------------------
xml操作真方便啊。。。像我这种就要写一堆
create table #base(fid varchar(4) not null,fname varchar(16) null)
insert into #base (fid,fname) values ('1002','粉尘')
insert into #base (fid,fname) values ('1007','燥音')

--select* from #base
create table #record(sid int not null,fid varchar(16) null)

insert into #record(sid,fid) values(1,'1002')
insert into #record(sid,fid) values(2,'1007')
insert into #record(sid,fid) values(3,'1002/1007')
;with mu as (
select 
t1.sid
,t3.fname
,row_number() over(PARTITION by t1.sid order by t2.number) as num
from #record t1
inner join master..spt_values t2 on t2.type='P' and CHARINDEX('/','/'+t1.fid,t2.number)=t2.number
inner join #base t3 on SUBSTRING(t1.fid,t2.number,CHARINDEX('/',t1.fid+'/',t2.number)-t2.number)=t3.fid
),mu2 as (
select sid,convert(varchar(max),fname) as fname,num
from mu 
where num=1
union all
select t1.sid,t2.fname+'/'+t1.fname,t1.num
from mu t1
inner join mu2 t2 on t1.sid=t2.sid and t1.num=t2.num+1
)
select t1.sid,t1.fname
from mu2 t1
where not exists(
select 1 
from mu2 t2
where t2.sid=t1.sid and t2.num>t1.num
)
/*
sid fname
1 粉尘
2 燥音
3 粉尘/燥音
*/



drop table #record
drop table #base
  相关解决方案