如何在Oracle sql

时间:2018-03-24 13:55:08

标签: sql oracle

这很好。

SELECT (CASE WHEN condition then s1 else s2 end) from table.

但我正在寻找一个执行多个语句的解决方案,如

SELECT (CASE WHEN condition then s1, s2, s3.. else s4, s5,s6 end) from table.

有没有办法在那时执行查询块,否则阻止或者做其他任何替代方法?

像这样。

select (case when (LENGTH(TRIM(TRANSLATE(substr(var, -2), ' +-.0123456789', ' '))) is NULL) then RTRIM(SUBSTR(var, -2)) as A, LTRIM(SUBSTR(var, 1, (LENGTH(var) - 3))) as B else RTRIM(SUBSTR(var, -4)) as A, LTRIM(SUBSTR(var, 1, (LENGTH(var) - 3))) as B end) from trade

目前我正在

错误,警告:

ORA-00905:缺少关键字

2 个答案:

答案 0 :(得分:1)

你无法以你想要的方式做你想做的事。

我会将条件放在子查询中,然后使用重复的case表达式:

select (case when is_numeric = 1 
             then rtrim(substr(var, -2))
             else rtrim(substr(var, -4)) as A,
        end) as a,
       (case when is_numeric = 1
             then ltrim(substr(var, 1, length(var) - 3))
             else ltrim(substr(var, 1, length(var) - 3))
        end) as B
from (select t.*,
             (case when LENGTH(TRIM(TRANSLATE(substr(var, -2), ' +-.0123456789', ' '))) is NULL
                   then 1 else 0
              end) as is_numeric
      from trade t
     ) t

除非我弄错了,B无论如何都有相同的定义,因此您可以将其简化为:

select (case when is_numeric = 1 
             then rtrim(substr(var, -2))
             else rtrim(substr(var, -4)) as A,
        end) as a,
       ltrim(substr(var, 1, length(var) - 3)) as B
from (select t.*,
             (case when LENGTH(TRIM(TRANSLATE(substr(var, -2), ' +-.0123456789', ' '))) is NULL
                   then 1 else 0
              end) as is_numeric
      from trade t
     ) t

答案 1 :(得分:-1)

单个表达式不能产生多个列 相反,您可以使用替代联合:

with tab as ( 
  select 1 as choice, var, RTRIM(SUBSTR(var, -2)) as A
        , LTRIM(SUBSTR(var, 1, (LENGTH(var) - 3))) as B 
  from table
  union all
  select 2 as choice, var, RTRIM(SUBSTR(var, -4)) as A
        , LTRIM(SUBSTR(var, 1, (LENGTH(var) - 3))) as B 
  from table
)
select tab.A, tab.B 
from tab 
where tab.choice = case when (LENGTH(TRIM(TRANSLATE(substr(tab.var, -2)
                                    , ' +-.0123456789', ' ')))  is NULL) 
                                then 1 
                                else 2 end
-- not tested
;