SQL逻辑运算符 - 尝试获得正确的结果

时间:2013-03-25 14:57:16

标签: sql sql-server

我想知道我对这些操作符的错误。

我最终试图获得一个人名单,其中p.TEST或p.DL中的一个缺失,但不是两个人都在同一个人身上。

 select ....
  from ....

    WHERE

 ((p.TEST is null OR p.DL is null) OR
 (p.TEST = 0 or p.DL = 0) OR
 (p.TEST = 1 or p.DL = 0) OR
 (p.TEST = 0 or p.DL = 1))

3 个答案:

答案 0 :(得分:1)

  

但不是两个人都在同一个人身上。

您的陈述中无法保证。

 ((p.TEST is null OR p.DL is null) OR  // if both are null this is true
 (p.TEST = 0 or p.DL = 0) OR           // if both are zero this is true
 (p.TEST = 1 or p.DL = 0) OR
 (p.TEST = 0 or p.DL = 1))

您必须明确检查:

((a is null) and (b is not null)) OR
((b is null) and (a is not null))
// etc. for zero values:
((a = 0) and (b  <> 0)) OR
((b = 0) and (a <> 0))
//...

即使这样,您也会获得a = 0b = null这样的结果,因此您可能需要对这些结果进行过滤。

答案 1 :(得分:1)

select ..
from ..
where 
    -- one missing 
    (isnull(p.test,0) = 0 or isnull(p.dl,0) = 0
    and 
    -- but not both
    not (isnull(p.test,0) = 0 and isnull(p.dl,0) = 0)

答案 2 :(得分:0)

我认为应该是

 ( 
   (p.TEST is null AND p.DL is not null) OR 
   (p.TEST is not null AND p.DL is null)
 )

......等等

这是因为你想知道什么时候出现而另一个缺席