这个查询AND和OR逻辑有什么问题

时间:2016-08-26 06:29:47

标签: sql select conditional

    select [Financial Year],  cast(sum(case when [IMU Visit] = 1 then 1 else 0 end) as float) as IMU_Visits from DEO_Visits
    where TotalSchool is null and visittype='regular'
    and ((Season = 'Winter' and Month  NOT in ('January','February'))
    OR (Season = 'Summer' and Month NOT in ('July','August')))
    group by  [Financial Year]
    having sum([IMU Visit]) > 0

据我所知,我已经正确地写了上面的查询。我想排除冬季的1月和2月月份以及夏季的7月和8月月份,但查询不起作用。它会返回93762 records天气,其中包含最后一个and .. OR

如果我只替换Not inIn,那么我会从查询中获得一些结果。这些是我想从结果中减去的记录。我究竟做错了什么?花很多时间在这个看似简单的问题上。感谢

更新

以下查询返回结果(基本上我想要排除)。我刚刚Not in

更改了In
    select [Financial Year],  cast(sum(case when [IMU Visit] = 1 then 1 else 0 end) as float) as IMU_Visits from DEO_Visits
    where TotalSchool is null and visittype='regular'
    and ((Season = 'Winter' and Month  in ('January','February'))
    OR (Season = 'Summer' and Month  in ('July','August')))
    group by  [Financial Year]
    having sum([IMU Visit]) > 0

4 个答案:

答案 0 :(得分:1)

从这样的逻辑中思考:

(A and B) or (C and D)

其中

  • A - >季节='冬天'
  • B - >月份('一月','二月')
  • C - >季节='夏天'
  • D - >月份('七月','八月')

你想要的是与上述条件相反的。换句话说

not ((A and B) or (C and D))

使用De Morgan定律(https://en.wikipedia.org/wiki/Logical_equivalence),你可以将其改为哈姆雷特的建议

not (A and B) and not (C and D)

您可以再次申请德摩根定律

(not A or not B) and (not C or not D)

因此,您还可以编写以下条件

(Season <> 'Winter' or Month  not in ('January','February'))
and (Season <> 'Summer' or Month not in ('July','August'))

或者最简单的方法是在您的情况下简单地添加NOT。坦率地说,我会选择这个,因为如果你回去重新阅读你的SQL查询,它可能是最容易理解的。

答案 1 :(得分:0)

你的逻辑对我来说是正确的。我不明白为什么要将Visits转换为float但是:

select [Financial Year],
       sum(case when [Visit] = 1 then 1 else 0 end) as Visits
from Visits
where TotalSchool is null and
      visittype = 'regular' and
      ((Season = 'Winter' and Month not in ('January', 'February')) or
       (Season = 'Summer' and Month not in ('July', 'August'))
      )
group by [Financial Year]
having sum([Visit]) > 0;

一种可能性是月份的拼写。如果月份为'Jan''Feb'等,则not in将始终通过。

答案 2 :(得分:0)

AND((季节=&#39;冬季&#39;月份不在(&#39; 1月&#39;,&#39; 2月&#39;)) AND(季节=&#39;夏季&#39;月份不在(&#39; 7月&#39;,&#39; 8月&#39;))

答案 3 :(得分:0)

尝试以下查询:

 select [Financial Year],  cast(sum(case when [IMU Visit] = 1 then 1 else 0  end) as float) as IMU_Visits from DEO_Visits
 where TotalSchool is null and visittype='regular' group by  [Financial Year]
 having sum([IMU Visit]) > 0
 MINUS
 select [Financial Year],  cast(sum(case when [IMU Visit] = 1 then 1 else 0 end) as float) as IMU_Visits from DEO_Visits
 where TotalSchool is null and visittype='regular'
 and ((Season = 'Winter' and Month  in ('January','February'))
 OR (Season = 'Summer' and Month  in ('July','August')))
 group by  [Financial Year]
 having sum([IMU Visit]) > 0

我知道它没有以任何方式进行优化,但正如您解释的那样,当您使用'in'时查询工作正常并且您想要减去这些结果时,上述查询应该可以正常工作。