日期:2014-05-17 浏览次数:20446 次
if not object_id('Class') is null drop table Class Go Create table Class([Student] nvarchar(2),[Course] nvarchar(2),[Score] INT,id DATETIME) Insert Class select N'张三',N'语文',78,'2012-01-01' union all select N'张三',N'数学',87,'2012-01-02'union all select N'张三',N'英语',82,'2012-01-03' union all select N'张三',N'物理',90,'2012-01-04' union all select N'李四',N'语文',65,'2012-01-05' union all select N'李四',N'数学',77,'2012-01-06' union all select N'李四',N'英语',65,'2012-01-07' union all select N'李四',N'物理',85,'2012-01-08' GO
declare @s nvarchar(4000) Select @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course] --isnull(@s+',','') 去掉字符串@s中第一个逗号 exec( 'select [Student],' +@s+ 'from (select student,course,score from Class WHERE ID>2012-01-01 ) a pivot ( max([Score]) for [Course] in('+@s+') )b ' )
Student 数学 物理 英语 语文 ------- ----------- ----------- ----------- ----------- 李四 77 85 65 65 张三 87 90 82 78 (2 行受影响)