【问题标题】:Case and Where logic appear similar but yield different resultsCase 和 Where 逻辑看起来相似但产生不同的结果
【发布时间】:2018-10-31 11:06:20
【问题描述】:

我收到一位同事的查询,其中包含如下 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 以不同的方式对待他们?

【问题讨论】:

  • 你能指出第一个查询选择的示例行,但第二个查询没有选择吗?
  • aircft_out_of_srvc_reason_cdmntnc_stn_cd 的任何列是否允许空值?
  • OR 很好。它被not (...)否定了

标签: sql case where teradata


【解决方案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)
      )

【讨论】:

  • 是的,我认为问题的根本原因是空值,即使 Eric 没有回应。
  • 这部分 where 的列不在原始查询中。包括它们之后,很明显这两列要么都为空,要么都不为空。不过我还是不明白,null in (x,y,z) or null in (a,b,c) 是否返回 true?
  • @EricEdLohmar 。 . .不会。几乎所有包含NULL 的比较都会返回NULL,在WHERE 子句中被视为false。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-21
  • 1970-01-01
  • 2022-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多