为什么WHERE条件加了没起效果?
新建表
if not object_id('Class') is null drop table ClassGoCreate table Class([Student] nvarchar(2),[Course] nvarchar(2),[Score] INT,id DATETIME)Insert Classselect N'张三',N'语文',78,'2012-01-01' union allselect N'张三',N'数学',87,'2012-01-02'union allselect N'张三',N'英语',82,'2012-01-03' union allselect N'张三',N'物理',90,'2012-01-04' union allselect N'李四',N'语文',65,'2012-01-05' union allselect N'李四',N'数学',77,'2012-01-06' union allselect N'李四',N'英语',65,'2012-01-07' union allselect 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 行受影响)