求SQL语法 列转行问题
表A:
ID I1 I2 I3 I4 I5
A1 a b c a,c a,b,f
B1 c d e f,e c
请教如何拆成下表
结果如下:
表B:
ID I
A1 a
A1 b
A1 c
A1 a
A1 c
A1 a
A1 b
A1 f
B1 c
B1 d
B1 e
B1 f
B1 e
B1 c
------解决方案----------------------取消第一个临时表,将其放到查询里面做为子表的做法.
create table tb(ID varchar(10),I1 varchar(10),I2 varchar(10),I3 varchar(10),I4 varchar(10),I5 varchar(10))
insert into tb values( 'A1 ', 'a ', 'b ', 'c ', 'a,c ', 'a,b,f ')
insert into tb values( 'B1 ', 'c ', 'd ', 'e ', 'f,e ', 'c ')
go
--1,建立一个辅助的临时表就可以了
SELECT TOP 8000 id = identity(int,1,1)
INTO # FROM syscolumns a, syscolumns b
--2,获取数据
SELECT
A.ID,
I = SUBSTRING(A.txt, B.ID, CHARINDEX( ', ', A.txt + ', ', B.ID) - B.ID)
FROM (select id , i1 + ', ' + i2 + ', ' + i3 + ', ' + i4 + ', ' + i5 txt from tb) A, # B
WHERE SUBSTRING( ', ' + a.txt, B.id, 1) = ', '
ORDER BY 1,2
GO
drop table tb,#
/*
ID I
---------- ----
A1 a
A1 a
A1 a
A1 b
A1 b
A1 c
A1 c
A1 f
B1 c
B1 c
B1 d
B1 e
B1 e
B1 f
(所影响的行数为 14 行)
*/
------解决方案----------------------原始数据:#test
create table #test(ID varchar(2),I1 varchar(1),I2 varchar(1),I3 varchar(1),I4 varchar(3),I5 varchar(5))
insert #test
select 'A1 ', 'a ', 'b ', 'c ', 'a,c ', 'a,b,f ' union all
select 'B1 ', 'c ', 'd ', 'e ', 'f,e ', 'c '
select top 100 tmpi