Case和Where逻辑看起来相似但产生不同的结果

时间:2018-05-21 18:40:53

标签: sql case where teradata

我收到了一位同事的查询,其中包含where语句,如下所示:

where ...
and case
    when    AOS.aircft_out_of_srvc_reason_cd in ('L','H')
         or AOS.mntnc_stn_cd in ('TLE','DWH') then 'Y'
    else 'N' end ='N'

如果我将其更改为以下

,我想我可以取出case
where ...
and not (   AOS.aircft_out_of_srvc_reason_cd in ('L','H')
         or AOS.mntnc_stn_cd in ('TLE','DWH'))

但这在某种程度上产生的记录不到原始记录数的10%。对我来说,两者中的逻辑看起来是一样的。有没有人知道为什么Teradata以不同的方式对待它们?

1 个答案:

答案 0 :(得分:1)

对此的等效逻辑:

where ... and
     (case when AOS.aircft_out_of_srvc_reason_cd in ('L', 'H') or
                AOS.mntnc_stn_cd in ('TLE', 'DWH')
           then 'Y'
           else 'N'
      end) = 'N'

基本上是:

where . . . and
      AOS.aircft_out_of_srvc_reason_cd not in ('L', 'H') and
      AOS.mntnc_stn_cd not in ('TLE', 'DWH')

(与您的not表达式相同)

唯一的问题是如果两列都是NULL,那么您应该包括:

where . . . and
      ( (AOS.aircft_out_of_srvc_reason_cd not in ('L', 'H') and
         AOS.mntnc_stn_cd not in ('TLE', 'DWH') and
        ) or
        (AOS.aircft_out_of_srvc_reason_cd is null and AOS.mntnc_stn_cd is null)
      )