如何使用在 case 之前定义了别名的 CASE?

WDr*_*rgn 3 oracle case alias

我如何在本示例(Oracle 数据库)中pop进一步使用别名case

select  
   (select sum(ccs_pop) from rap4) as pop,
case 
    when pop+x=a+b+c then pop+x
end as sum1,
case 
    when pop+y=d+e+f then pop+y
end as sum2
from rap4
Run Code Online (Sandbox Code Playgroud)

想法是我在复杂的情况下需要“pop”,并且在很多句子中都需要“pop”,我需要使用别名或其他东西......

ype*_*eᵀᴹ 6

好的,我将采用提供的示例,并对其进行一些修改:

select  
    (<insanely complex expression>) as pop,
    case 
        when pop is null then 'isnull'
    end
from rap4 ;
Run Code Online (Sandbox Code Playgroud)

上述当然会产生错误,因为SELECT列表中定义的别名不能用于同一SELECT列表或(同一级别)WHEREGROUP BY子句中的另一个表达式中。

但是,您可以做的是复制表达式:

select  
    (<insanely complex expression>) as pop,
    case 
        when <insanely complex expression> is null then 'isnull'
    end
from rap4 ;
Run Code Online (Sandbox Code Playgroud)

或使用派生表:

select
    pop,
    case 
        when pop is null then 'isnull'
    end
from 
    ( select  
          (<insanely complex expression>) as pop
      from rap4
    ) t ;
Run Code Online (Sandbox Code Playgroud)

或使用公用表表达式 (CTE):

with cte as
  ( select  
        (<insanely complex expression>) as pop
    from rap4
 )
select
    pop,
    case 
        when pop is null then 'isnull'
    end
from cte ;
Run Code Online (Sandbox Code Playgroud)