【问题标题】:How to handle multiple parameter in case statement in ORACLEORACLE如何处理case语句中的多个参数
【发布时间】:2020-10-12 18:51:59
【问题描述】:

我使用 ORACLE 查询。我陷入了与以下代码/条件非常相似的查询中。 我有多个条款,根据条款,具有多个值的条件应如下所示。

条款:

  1. 第一季度

  2. 第二季

  3. 上半场

    MONTHS IN (CASE WHEN terms = 'First Quarter' THEN ('JAN','FEB','MAR') 
                     WHEN terms = 'Second Quarter' THEN ('APR','MAY','JUN')
                     WHEN terms = 'First Half' THEN ('JAN','FEB','MAR','APR','MAY','JUN')
                     ELSE ('JUL','AUG','SEP','OCT','NOV','DEC')
                     END )
    

当我执行上述相同的查询时,错误消息显示为 ORA-00907 - 缺少右括号 我找不到原因。

请就修复和性能提供建议,因为我在原始查询中有多个条件。

提前致谢。

【问题讨论】:

    标签: sql oracle select case where-clause


    【解决方案1】:

    这是一种选择;第 1 - 8 行的示例数据。您可能感兴趣的查询从第 9 行开始。根据您使用的工具,'&&terms' 可能看起来与此不同(例如:terms)。这是 SQL*Plus。另外,我用缩写代替了你的“宿舍”之类的东西(不想打字那么多)。

    SQL> with months (mon, num) as
      2  (select 'jan', 1 from dual union all
      3   select 'feb', 2 from dual union all
      4   select 'mar', 3 from dual union all
      5   select 'apr', 4 from dual union all
      6   select 'may', 5 from dual union all
      7   select 'jun', 6 from dual
      8  )
      9  select *
     10  from months
     11  where mon in
     12    (select *
     13       from table(sys.odcivarchar2list('jan', 'feb', 'mar'))
     14       where '&&terms' = 'FQ'
     15     union all
     16     select *
     17       from table(sys.odcivarchar2list('apr', 'may', 'jun'))
     18       where '&&terms' = 'SQ'
     19     union all
     20     select *
     21       from table(sys.odcivarchar2list('jan', 'feb', 'mar', 'apr', 'may', 'jun'))
     22       where '&&terms' = 'FH'
     23    )
     24 order by num;
    
    Enter value for terms: SQ
    
    MON        NUM
    --- ----------
    apr          4
    may          5
    jun          6
    

    --

    SQL> undefine terms
    SQL> /
    Enter value for terms: FH
    
    MON        NUM
    --- ----------
    jan          1
    feb          2
    mar          3
    apr          4
    may          5
    jun          6
    
    6 rows selected.
    
    SQL>
    

    【讨论】:

      【解决方案2】:

      您可以使用布尔逻辑来描述您的条件,而不是 case 表达式:

         (terms = 'First Quarter'  and months in ('JAN', 'FEB', 'MAR'))
      or (terms = 'Second Quarter' and months in ('APR', 'MAY', 'JUN'))
      or (terms = 'First Half'     and months in ('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN'))
      

      这可以缩短一点:

         (terms in ('First Quarter',  'First Half') and months in ('JAN', 'FEB', 'MAR'))
      or (terms in ('Second Quarter', 'First Half') and months in ('APR', 'MAY', 'JUN'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-15
        • 1970-01-01
        • 1970-01-01
        • 2022-06-21
        • 1970-01-01
        • 2017-02-20
        • 1970-01-01
        相关资源
        最近更新 更多