【问题标题】:Case When Condition in Where Clause. Use filter condition if it matches the case when condition only在 Where 子句中的 Case When 条件。如果仅与条件匹配,则使用过滤条件
【发布时间】:2016-12-19 08:20:20
【问题描述】:

是否可以在 where 子句中使用 case when 条件来过滤 select 语句。 例如:

Select * from table_name 
where source ='UHC'
and 
to_char(termdate,'YYYYMM') <= '201603';

但我希望第二个过滤条件仅在策略编号为“1”时才起作用。例如:

case when policy_number = '1' then to_char(termdate,'YYYYMM') <= '201603';

如果策略编号不是 1,那么只有第一个 where 子句应该起作用,但如果策略编号是 1,那么两个 where 子句都应该起作用。 我希望我把我的情况说清楚了。

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    你根本不需要案例:

    Select * from table_name 
    where source ='UHC'
    and ((policy_number = '1' and to_char(termdate,'YYYYMM') <= '201603') 
         or nvl(policy_number, '0') != '1');
    

    case 条件如下:

    where source ='UHC' and case when policy_number = '1' then to_char(termdate,'YYYYMM') else '000000' end <= '201603');
    

    否则你需要的东西总是小于'201603'。这里的另一个问题是为什么您将数字作为 varchars 进行比较?真的是你需要的吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-09
      • 2023-03-27
      相关资源
      最近更新 更多