sql&oracle中case语句中多参数的处理

yftpprvb  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(232)

我正在使用oracle查询。我卡在我的查询,这是非常类似于下面的代码/条件。我有多个条件,基于这些条件,具有多个值的条件应按如下方式传递。
条款:
第一季度
第二季度
上半场

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-missing right paranthesis,我找不到原因。
请提供有关修复和性能方面的建议,因为我在原始查询中有多个条件。
提前谢谢。

r7knjye2

r7knjye21#

您可以使用布尔逻辑来描述您的条件,而不是 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'))
gab6jxml

gab6jxml2#

这里有一个选择;第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>

相关问题