具有多个AND和OR的SQL CASE WHEN

时间:2018-08-22 20:22:54

标签: sql

能否请您告诉我下面的SQL代码是否有意义。我在ANDs中使用了多个ORCASE WHEN。 谢谢你的帮助!

SELECT id, period,
 CASE WHEN state = 'group8' AND mathscore = 0 AND manager = '' OR manager ISNULL 
 THEN 'Tom' ELSE manager END AS mgr, 

 CASE WHEN state = 'group8' AND mathscore = 0 AND associate = '' OR associate 
 ISNULL THEN 'Dick' ELSE associate END AS asso,

 CASE WHEN state = 'group8' AND mathscore = 0 AND analyst = '' OR analyst ISNULL 
 THEN 'Harry' ELSE analyst END AS a

 FROM class.sections 

2 个答案:

答案 0 :(得分:2)

在使用AND和OR时,应将其括在括号中,以免产生不必要的结果。即:

CASE WHEN (state = 'group8' AND mathscore = 0)
AND (manager = '' OR manager ISNULL)
THEN 'Tom' ELSE manager END AS mgr

不同于:

CASE WHEN (state = 'group8' AND mathscore = 0 AND manager = '')
OR manager ISNULL 
THEN 'Tom' ELSE manager END AS mgr

答案 1 :(得分:0)

没有示例数据可使用,我打赌您正在寻找类似的东西,您的空格和NULL加上括号分组。

另外,我将您的ISNULL(某些语言中的函数)更改为IS NULL(无论如何在SQL Server中为状态)。

SELECT
  id
 ,period
 ,CASE
    WHEN state = 'group8'
         AND mathscore = 0
         AND (manager = ''
             OR manager IS NULL) THEN 'Tom'
    ELSE manager
  END AS mgr
 ,CASE
    WHEN state = 'group8'
         AND mathscore = 0
         AND (associate = ''
             OR associate IS NULL) THEN 'Dick'
    ELSE associate
  END AS asso
 ,CASE
    WHEN state = 'group8'
         AND mathscore = 0
         AND (analyst = ''
             OR analyst IS NULL) THEN 'Harry'
    ELSE analyst
  END AS a
FROM
  class.sections;