在 sql 查询中为一个条件添加 where 条件

adding a where condition for one criteria in sql query

我需要为 SQL 查询添加一个 where 条件,这意味着当部门 ID 变为 9 时,我只需要那个 where 条件,否则我不需要。

我写了下面的查询,方法是否正确?

SELECT 
b.DeptId,
b.DeptName,
a.SurveyID,
a.SurveyName,
a.Status,
a.AllUsers, 
IsNull(a.SelectedUsers,'') as SelectedUsers,
a.OpenDate,
a.CloseDate,
e.Role as RoleName 
from Surveys a 
inner join Departments b 
on a.deptid=b.deptid 
left outer join
 surveyUsers c 
on c.surveyid=a.SurveyID 
and c.empCode= 9902
left outer join [360HRSurveyEmployee] d 
on d.surveyid=a.SurveyID 
left outer join [360HRSurvey] e 
on e.sempid = c.empCode 
and e.empid = d.empid 
where ( c.empCode= 9902 or a.AllUsers = 1 ) 
and a.status in (1) 
and a.OpenDate <= '6/9/2015' 
and a.CloseDate >= '6/9/2015'
and CASE WHEN DeptId == 9 
         THEN e.Role IS NOT NULL END
 order by b.DeptID,a.SurveyID 

注意上面查询中我添加大小写的最后三行:

and CASE WHEN DeptId == 9 
         THEN e.Role IS NOT NULL END
 order by b.DeptID,a.SurveyID 

我也遇到语法错误

Incorrect syntax near '='.
and CASE WHEN DeptId == 9

您只需要一个 = 符号即可进行此比较。

您需要使用单个 =

CASE WHEN DeptId = 9 
     THEN e.Role END

你到底想用这条线达到什么目的? THEN e.Role IS NOT NULL END

如果我没理解错的话,您只需要 DeptId 不为 9 或 DeptId 不为空的行。另外,你对大写一致性的严重漠视伤害了我。这是什么野兽?!

SELECT
    b.DeptID, b.DeptName,
    a.SurveyID, a.SurveyName, a.Status, a.AllUsers,
    ISNULL(a.SelectedUsers,'') as SelectedUsers,
    a.OpenDate, a.CloseDate, e.Role as RoleName
FROM
    Surveys AS a
    INNER JOIN Departments AS b
        ON a.DeptID = b.DeptID
    LEFT OUTER JOIN SurveyUsers AS c
        ON (c.SurveyID = a.SurveyID AND c.EmpCode = 9902)
    LEFT OUTER JOIN [360HRSurveyEmployee] AS d
        ON d.SurveyID = a.SurveyID
    LEFT OUTER JOIN [360HRSurvey] AS e
        ON (e.EmpID = c.EmpCode AND e.EmpID = d.EmpID)
WHERE
    (
        c.EmpCode = 9902
        OR a.AllUsers = 1
    )
    AND a.Status = 1
    AND a.OpenDate <= '6/9/2015'
    AND a.CloseDate >= '6/9/2015'
    AND (
        a.DeptID != 9
        OR e.Role IS NOT NULL
    )
ORDER BY
    a.DeptID,
    a.SurveyID;