概述
在使用SQL Server数据库的过程中我们经常会遇到需要将查询结果从纵表转成横表的问题,下面将用一个简单的实例说明如何使用动态查询语句来解决这一问题。
先创建一个表并插入数据如下(纵表):
create table StudentScores
(
StudentName varchar(16),
Subject varchar(16),
Score smallint
)
insert into StudentScores
values('张三','语文',85)
insert into StudentScores
values('张三','数学',90)
insert into StudentScores
values('张三','英语',86)
insert into StudentScores
values('李四','语文',92)
insert into StudentScores
values('李四','数学',87)
insert into StudentScores
values('李四','英语',90)
此时 select * from StudentScores 直接查询结果如下:
用需要生成横表字段名的列数据创建一个临时表并去重:
select distinct Subject as Sub into #temp from StudentScores
最后使用如下语句转成横表:
declare @SQL varchar(max) --定义变量@SQL
--拼接查询语句
set @SQL='select StudentName,'
select @SQL=@SQL+'sum(case when Subject='''+Sub+''' then Score else 0 end) as '+Sub+' , ' from #temp
select @SQL= LEFT(@SQL, len(@SQL)-1)
set @SQL=@SQL+ 'from StudentScores group by StudentName'
--执行查询
exec(@SQL)
查询结果如下:
在SQL Server中有一个内置的函数PIVOT也能够实现同样的查询效果。详细的使用方法请查看SQL Server行列转换