现在的位置: 首页 > 综合 > 正文

在论坛中出现的比较难的sql问题:1(字符串分拆+行转列问题)

2014年07月28日 ⁄ 综合 ⁄ 共 1354字 ⁄ 字号 评论关闭

最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了。

所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。

1、求SQL遍历截取字符串

http://bbs.csdn.net/topics/390648078


从数据库中读取某一张表(数据若干),然后将某一字段进行截取。
比如:
字段A    字段B
a/a/c      x
a/b/c      x

切出来就变成:

字段1      字段2         字段3       字段B
a            a            c            x
b            b            c            x

数据不止一条  ,是遍历切取,求完整sql(从读取到遍历到截取到输出),求教。

另外还需要把列头进行排序,结果也需要按照字段1,字段2...进行排序


我的解法:

if object_id('[tb]') is not null drop table [tb]
go 

create table [tb](A varchar(40),B varchar(10))

insert [tb]
select 'xx/xx/xx/xx/xx/xx','x' union all
select 'yy/yy/yy/yy/yy/yy','x'
go

if OBJECT_ID('tempdb..#temp1') is not null
   drop table #temp1

if OBJECT_ID('tempdb..#temp2') is not null
   drop table #temp2

select *,IDENTITY(int,1,1) id into #temp1
from tb

declare @sql nvarchar(3000)
declare @orderby nvarchar(100)
set @sql = '';
set @orderby = '';

;with t
as
(
select ID,
       SUBSTRING(t.A, number ,CHARINDEX('/',t.a+'/',number)-number) as v,
       b,
       row_number() over(partition by id order by @@servername) as rownum
from #temp1 t,master..spt_values s
where s.number >=1
and s.type = 'P'
and SUBSTRING('/'+t.A,s.number,1) = '/'
)

select * into #temp2
from t


select @sql = @sql + ',max(case when rownum = '+CAST(rownum as varchar)+
                     ' then v else null end) as 列'+CAST(rownum as varchar) ,
       @orderby  = @orderby + ',列'+CAST(rownum as varchar)
              
                     
from #temp2
group by rownum
order by rownum  --加了排序




set @sql = 'select '+STUFF(@sql,1,1,'')+ ',b' +
           ' from #temp2 group by id,b order by '+
           stuff(@orderby,1,1,'')
           
--select @sql

exec(@sql)   
/*
列1	列2	列3	列4	列5	列6	b
xx	xx	xx	xx	xx	xx	x
yy	yy	yy	yy	yy	yy	x
*/        

抱歉!评论已关闭.