简体   繁体   中英

Compare 1 field from sub query against other?

I am trying to compare two fields in oracle select query as part of case statement one of which is coming from sub query but I get error.

Eg

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

Error ORA-00904: TWO invalid identifier

Thoughts how can rewrite this?

Thanks in advance!

You cant use the alias, so you have to rewrite the data source and subquery.

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

Result

one two match
1   2   NOTEQUAL

The problem is you cant use the alias on the same level, you need to do a subquery or a 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

Use a simple subquery

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM