需求貼:
http://topic.csdn.net/u/20120204/10/8b902fd2-8909-4ed9-b534-4a1a72454eff.html#r_77443331
需求簡介:
比如:YYYYN, 結果處理為:人1,人2,人3,人4
分析:
貌似就是一個字串的替換,如果是'Y'替換成'人'+Y的所在位置的編號。
解決方案:
declare @T table (id int,col varchar(5))insert into @Tselect 1,'YYYYN' union allselect 2,'YNNNY' union allselect 3,'NNNYN' union allselect 4,'YYNYN'--1.第一種方法:case when--最直觀的處理方式 select id,col=left(col,len(col)-1) from ( select id,col= case when left(col,1)='Y' then '人1,' else '' end+ case when substring(col,2,1)='Y' then '人2,' else '' end+ case when substring(col,3,1)='Y' then '人3,' else '' end+ case when substring(col,4,1)='Y' then '人4,' else '' end+ case when substring(col,5,1)='Y' then '人5,' else '' end from @T) a/*id col----------- --------------------1 人1,人2,人3,人42 人1,人53 人44 人1,人2,人4*/--2.使用自訂函數 --建立函數create function fn_GetPersonCount( @str varchar(5))returns varchar(20)asbegin declare @result varchar(20) set @result='' declare @i int set @i=0 while(charindex('Y',@str)>0) begin set @result=@result+'人'+ltrim(charindex('Y',@str)+@i)+',' set @str=right(@str,len(@str)-charindex('Y',@str)) set @i=@i+1 end set @result=left(@result,len(@result)-1) return @resultenddeclare @T table (id int,col varchar(5))insert into @Tselect 1,'YYYYN' union allselect 2,'YNNNY' union allselect 3,'NNNYN' union allselect 4,'YYNYN'select id,col=dbo.fn_GetPersonCount(col) from @T/*id col----------- --------------------1 人1,人2,人3,人42 人1,人53 人44 人1,人2,人4*/--3.合并列值declare @T table (id int,col varchar(5))insert into @Tselect 1,'YYYYN' union allselect 2,'YNNNY' union allselect 3,'NNNYN' union allselect 4,'YYNYN';with maco as(select a.*,'人'+ltrim(b.number+1) as c1 from @T a,master..spt_values b where b.type='p' and b.number <5 and substring(col,0+right(number+1,1),1)='Y')select id, col=stuff((select ','+c1 from maco t where id=maco.id for xml path('')), 1, 1, '')from maco group by id/*id col----------- --------------------1 人1,人2,人3,人42 人1,人53 人44 人1,人2,人4*/