那位高手请帮帮我
时间:2011-11-14
来源:互联网
是否可以以某一列为依据将一行分解为多行的SQL语句?
举例如下:
表X(a,b,c)
a b c
---------------------
1 x+y t1
2 q+w+e t2
3 z+aa+bb+cc+dd t3
...
按b列以+号分解,+号的个数不定,得到下表
a b c
----------
1 x t1
1 y t1
2 q t2
2 w t2
2 e t2
3 z t3
3 aa t3
3 bb t3
3 cc t3
3 dd t3
举例如下:
表X(a,b,c)
a b c
---------------------
1 x+y t1
2 q+w+e t2
3 z+aa+bb+cc+dd t3
...
按b列以+号分解,+号的个数不定,得到下表
a b c
----------
1 x t1
1 y t1
2 q t2
2 w t2
2 e t2
3 z t3
3 aa t3
3 bb t3
3 cc t3
3 dd t3
作者: zhqzhm 发布时间: 2011-11-14
SQL code
--> --> (Roy)生成測試數據 if not object_id('X') is null drop table X Go Create table X([a] int,[b] nvarchar(13),[c] nvarchar(2)) Insert X select 1,N'x+y',N't1' union all select 2,N'q+w+e',N't2' union all select 3,N'z+aa+bb+cc+dd',N't3' Go Select a.a,[b]=substring(a.b,b.number,charindex('+',a.b+'+',b.number)-b.number),a.c from X as a,master.dbo.spt_values as b where b.type='P' and substring('+'+a.[b],b.number,1)='+' /* a b c 1 x t1 1 y t1 2 q t2 2 w t2 2 e t2 3 z t3 3 aa t3 3 bb t3 3 cc t3 3 dd t3 */
作者: roy_88 发布时间: 2011-11-14
SQL code
其它方法参照 拆分表: --> --> (Roy)生成測試數據 if not object_id('Tab') is null drop table Tab Go Create table Tab([Col1] int,[COl2] nvarchar(5)) Insert Tab select 1,N'a,b,c' union all select 2,N'd,e' union all select 3,N'f' Go SQL2000用辅助表: if object_id('Tempdb..#Num') is not null drop table #Num go select top 100 ID=Identity(int,1,1) into #Num from syscolumns a,syscolumns b Select a.Col1,COl2=substring(a.Col2,b.ID,charindex(',',a.Col2+',',b.ID)-b.ID) from Tab a,#Num b where charindex(',',','+a.Col2,b.ID)=b.ID --也可用 substring(','+a.COl2,b.ID,1)=',' SQL2005用Xml: select a.COl1,b.Col2 from (select Col1,COl2=convert(xml,'<root><v>'+replace(COl2,',','</v><v>')+'</v></root>') from Tab)a outer apply (select Col2=C.v.value('.','nvarchar(100)') from a.COl2.nodes('/root/v')C(v))b SQL05用CTE: ;with roy as (select Col1,COl2=cast(left(Col2,charindex(',',Col2+',')-1) as nvarchar(100)),Split=cast(stuff(COl2+',',1,charindex(',',Col2+','),'') as nvarchar(100)) from Tab union all select Col1,COl2=cast(left(Split,charindex(',',Split)-1) as nvarchar(100)),Split= cast(stuff(Split,1,charindex(',',Split),'') as nvarchar(100)) from Roy where split>'' ) select COl1,COl2 from roy order by COl1 option (MAXRECURSION 0) 生成结果: /* Col1 COl2 ----------- ----- 1 a 1 b 1 c 2 d 2 e 3 f */
作者: roy_88 发布时间: 2011-11-14
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28