SQL列转行
生成
sql代码
生成静态: select * from (select sname,[Course ] ='数学',[Score]=[数学] from Tb_students union all select sname,[Course]='英语',[Score]=[英语] from Tb_students union all select sname,[Course]='语文',[Score]=[语文] from Tb_students)t order by sname,case [Course] when '语文' then 1 when '数学' then 2 when '英语' then 3 end go --列转行的静态方案:UNPIVOT,sql2005及以后版本 SELECT sname,Subject, grade from dbo.Tb_students unpivot(grade for Subject in([语文],[数学],[英语]))as up GO --列转行的动态方案:UNPIVOT,sql2005及以后版本 --因为行是动态所以这里就从INFORMATION_SCHEMA.COLUMNS视图中获取列来构造行,同样也使用了XML处理。 declare @s nvarchar(4000) select @s=isnull(@s+',','')+quotename(Name) from syscolumns where ID=object_id('Tb_students') and Name not in('sname') order by Colid exec('select sname,[Subject],[grade] from Tb_students unpivot ([grade] for [Subject] in('+@s+'))b') go select sname,[Subject],[grade] from Tb_students unpivot ([grade] for [Subject] in([数学],[英语],[语文]))b