日期:2014-05-17  浏览次数:20407 次

为什么WHERE条件加了没起效果?
新建表
SQL code
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

行列转换语句,其中数据源中有WHERE条件 WHERE ID>2012-01-01
SQL code
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 '
                )


可是结果中,张三的语文成绩没有去掉,这该怎么改语句?
SQL code
Student 数学          物理          英语          语文
------- ----------- ----------- ----------- -----------
李四      77          85          65          65
张三      87          90          82          78

(2 行受影响)




------解决方案--------------------
WHERE ID>''2012-01-01 ''


替换一下

日期字段要加引号,不加引号就相当于把2012-01-01 计算出来 2000 在转换为datetime
 select cast(2012-01-01 as datetime),cast(2000 as datetime)

正常情况一个单引号就好了,但是你这个是在引号里面 所以需要两个单引号。