SQL条件where语句

时间:2013-05-12 20:20:10

标签: sql-server-2008 case conditional-statements

我编写了以下sql语句,但我不确定如何编写where语句,因为它是有条件的。所以我有:

declare @subject varchar(100)

select surname, forename, result 
from student 
join subject on subject.upn = student.upn 
where...

我想写的是sql:

where
if subject = 'English' then subject=@subject and KS2en=''
or if subject = 'Maths' then subject = @subject and KS2ma = ''
or if subject <> 'Maths' and <> 'English' then subject = @subject and KS2av = ''

我认为这可以在逻辑上完成,也可以使用case,但我现在有点亏。

以下是表格:

学生

UPN | Surname | Forename | KS2en | KS2Ma | KS2av

主题

UPN | Subject

所有都是varchar。

2 个答案:

答案 0 :(得分:1)

如下所示会做到这一点。

SELECT surname,
       forename,
       result
FROM   student
       JOIN subject
         ON subject.upn = student.upn
WHERE  subject.subject = @subject
       AND '' = CASE @subject
                  WHEN 'English' THEN KS2en
                  WHEN 'Maths' THEN KS2ma
                  ELSE KS2av
                END 

我假设subject不可为空。如果是,则上述查询的语义与伪代码略有不同。

答案 1 :(得分:1)

Where限制返回的行数,您希望根据条件返回不同的列值。

因此,您必须通过Where将条件包含在选择中,而不是使用CASE

DECLARE @subject VARCHAR(100) 

SELECT surname, 
       forename, 
       subject=@subject, 
       KS2en=CASE 
               WHEN subject = 'Engish' THEN '' 
               ELSE ks2en 
             END, 
       KS2ma=CASE 
               WHEN subject = 'Maths' THEN '' 
               ELSE ks2ma 
             END, 
       KS2av=CASE 
               WHEN subject NOT IN( 'Maths', 'English' ) THEN '' 
               ELSE ks2av 
             END 
FROM   student 
       JOIN subject 
         ON subject.upn = student.upn