case子句在where子句sql server里面

时间:2015-06-17 08:40:30

标签: sql-server case

我想在where子句中放置一个case条件,即如果第二个表的semester column为null,我需要过滤semester is null所在的列。如果没有,我需要在另一个条件下过滤数据。

// 如果学期为null,我需要查询如下:

select * from tbl_courses tc
    left join tbl_exams te on tc.courseID = te.courseID
    where te.gradeID=10 and 
    te.semester is null

// 如果学期不为null,则查询应为

select * from tbl_courses tc
left join tbl_exams te on tc.courseID = te.courseID
where te.gradeID=10 and 
te.semester is null

对于此要求,我如何从sql本身编写单个查询,如下所示:

select * from tbl_courses tc
left join tbl_exams te on tc.courseID = te.courseID
where te.gradeID=10 and 
(case when te.semester is null 
  then te.semester is null
  else te.semester = tc.semester END)  

任何方式这都不对。请帮助我

1 个答案:

答案 0 :(得分:2)

假设你的第二个选择陈述应该是:

select * from tbl_courses tc
left join tbl_exams te on tc.courseID = te.courseID
where te.gradeID=10 
and te.semester = tc.semester

试试这个:

select * 
from tbl_courses tc
left join tbl_exams te on tc.courseID = te.courseID
where te.gradeID=10 
and (
     te.semester = tc.semester
     OR te.semester is null
)