1、字符串分拆+行转列问题
来源:互联网 发布:关于提供数据的回函 编辑:程序博客网 时间:2024/04/29 11:01
最近看到一些比较好的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 allselect 'yy/yy/yy/yy/yy/yy','x'goif OBJECT_ID('tempdb..#temp1') is not null drop table #temp1if OBJECT_ID('tempdb..#temp2') is not null drop table #temp2select *,IDENTITY(int,1,1) id into #temp1from tbdeclare @sql nvarchar(3000)declare @orderby nvarchar(100)set @sql = '';set @orderby = '';;with tas(select ID, SUBSTRING(t.A, number ,CHARINDEX('/',t.a+'/',number)-number) as v, b, row_number() over(partition by id order by @@servername) as rownumfrom #temp1 t,master..spt_values swhere s.number >=1and s.type = 'P'and SUBSTRING('/'+t.A,s.number,1) = '/')select * into #temp2from tselect @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 #temp2group by rownumorder by rownum --加了排序set @sql = 'select '+STUFF(@sql,1,1,'')+ ',b' + ' from #temp2 group by id,b order by '+ stuff(@orderby,1,1,'') --select @sqlexec(@sql) /*列1列2列3列4列5列6bxxxxxxxxxxxxxyyyyyyyyyyyyx*/
0 0
- 1、字符串分拆+行转列问题
- 在论坛中出现的比较难的sql问题:1(字符串分拆+行转列问题 SQL遍历截取字符串)
- 分拆统计字符串
- 字符串分拆查询
- 字符串分拆函数
- 短信字符串分拆
- 短信字符串分拆
- 字符串分拆函数
- 短信字符串分拆
- 短信字符串分拆
- 短信字符串分拆
- 短信字符串分拆
- 短信字符串分拆
- 短信字符串分拆
- 字符串分拆查询
- 分拆统计字符串
- 字符串分拆查询
- 分拆统计字符串
- 用OpenSSL做自签名的证书(by quqi99)
- C++replace()函数用法
- String,StringBuffer,StringBuilder的区别
- R Programming -- real-world data
- 云“价值链”分析
- 1、字符串分拆+行转列问题
- 如何减少TIME_WAIT的数量
- 始于欣赏,止于爱情
- IOS开发之----常用函数和常数
- vim 字符编码
- 旋转卡壳法求凸包的直径
- 第三方
- 实现Cocos2d-x追踪子弹
- jsp页面倒计时、javascript的MD5加密