表A:
A B F1 F2 F3
-------------------------------------
A1 B1 1 2 NULL
A1 B2 NULL 2 1
A2 B1 1 NULL NULL
A2 B2 NULL 1 1
通过SQL想要的结果:
A1 B1 F1
A1 B1 F2
A1 B2 F2
A1 B2 F3
A2 B1 F1
A2 B2 F2
A2 B2 F3如果F1、F2、F3值大于0,则作为第三列与A和B列形成一条记录,并且值以列名称替代需要动态的SQL,因为实际情况不止F1、F2、F3,而是F1到F131,100多列。SQL行列转换
A B F1 F2 F3
-------------------------------------
A1 B1 1 2 NULL
A1 B2 NULL 2 1
A2 B1 1 NULL NULL
A2 B2 NULL 1 1
通过SQL想要的结果:
A1 B1 F1
A1 B1 F2
A1 B2 F2
A1 B2 F3
A2 B1 F1
A2 B2 F2
A2 B2 F3如果F1、F2、F3值大于0,则作为第三列与A和B列形成一条记录,并且值以列名称替代需要动态的SQL,因为实际情况不止F1、F2、F3,而是F1到F131,100多列。SQL行列转换
declare @sql varchar(max) =''
select @sql=@sql+'union all select a,b,'+''''+
name+''''+' from a where '+name+' is not null '
from sys.columns where object_id in(
select object_id from sys.objects where name='a')
and name not in('a','b')
set @sql=SUBSTRING(@sql,10,len(@sql))+' order by 1,2,3'
exec( @sql)
declare @sql nvarchar(4000)
set @sql=''
select @sql=@sql+
'union all select a,b,'+''''+ name+''''+' from a where '+name+' is not null '
from syscolumns where id in
( select id from sysobjects where name='a')
and name not in('a','b')
set @sql=SUBSTRING(@sql,10,len(@sql))+' order by 1,2,3'
exec(@sql)
另外自己的笨办法:
create table B
(A nvarchar(50),
B nvarchar(50),
C nvarchar(50))declare @i int
declare @sqlstr nvarchar(1000)set @i=1while @i<=3
begin
set @sqlstr='Insert into B (A,B,C) select A,B,''F'+cast(@i as nvarchar)+''' from A where isnull(F'+cast(@i as nvarchar)+',0)>0'
exec(@sqlstr)
set @i=@i+1
endselect * from B
if not object_id('ClassDeng') is null
drop table ClassDeng
Go
Create table ClassDeng([Student] nvarchar(2),[数学] int,[物理] int,[英语] int,[语文] int,[化学] int)
Insert ClassDeng
select N'李四',77,85,65,65,88 union all
select N'张三',87,90,82,78,87 union all
select N'麻子',67,64,77,89,58
Go
---
student 数学 物理 英语 语文 化学
李四 77 85 65 65 88
张三 87 90 82 78 87
麻子 66 64 77 89 58 declare @s nvarchar(4000)
select @s=isnull(@s+' union all ','')+'select [Student],[Course]='+quotename(Name,'''')
+',[Score]='+quotename(Name)+' from ClassDeng'from syscolumns
where ID=object_id('ClassDeng') and Name not in('Student')
order by Colid exec('select * from ('+@s+')t order by [Student],[Course]')
-----运行结果
student Course Score
李四 数学 77
李四 物理 85
李四 英语 65
李四 语文 65
李四 化学 88
张三 数学 87
张三 物理 90
张三 英语 82
张三 语文 78
张三 化学 87
麻子 数学 66
麻子 物理 64
麻子 英语 77
麻子 语文 89
麻子 化学 58
====================
希望能帮到你。