比较子查询中的1个字段与其他字段?

时间:2017-08-09 22:04:00

标签: sql oracle select

我试图比较oracle select query中的两个字段作为case语句的一部分,其中一个来自子查询,但是我收到了错误。

E.g

select 1 as one, 
       (select 2 from dual) as two,
       case when one=two then 'EQUAL'
            else 'NOTEQUAL'
       end match
from dual;

错误ORA-00904:两个无效标识符

想怎么能改写这个?

提前致谢!

3 个答案:

答案 0 :(得分:1)

您无法使用别名,因此您必须重写数据源和子查询。

SELECT 1 as one,
       (SELECT 2 FROM dual) as two,
       CASE WHEN 1 = (SELECT 2 FROM dual)
            THEN 'EQUAL'
            ELSE 'NOTEQUAL' 
        END match
  FROM dual

结果

one two match
1   2   NOTEQUAL

答案 1 :(得分:0)

问题是你不能在同一级别使用别名,你需要做一个子查询或一个cte

WITH step1 as (
    select 1 as one
    from dual
), step2 as (
    select 2 as two
    from dual
)
SELECT case when one=two then 'EQUAL'
            else 'NOTEQUAL'
       end match
FROM step1
CROSS JOIN step2

答案 2 :(得分:0)

使用简单的子查询

Select t.*,
       case when one=two then 'EQUAL'
            else 'NOTEQUAL'
       end match
From (
    select 1 as one, 
           (select 2 from dual) as two
    from dual
) t;