문제

Is there a way to use a calculated field in the where clause?

I want to do something like

SELECT a, b, a+b as TOTAL FROM (
   select 7 as a, 8 as b FROM DUAL
   UNION ALL
   select 8 as a, 8 as b FROM DUAL
   UNION ALL
   select 0 as a, 0 as b FROM DUAL
)
WHERE TOTAL <> 0
;

but I get ORA-00904: "TOTAL": invalid identifier.

So I have to use

SELECT a, b, a+b as TOTAL FROM (
   select 7 as a, 8 as b FROM DUAL
   UNION ALL
   select 8 as a, 8 as b FROM DUAL
   UNION ALL
   select 0 as a, 0 as b FROM DUAL
)
WHERE a+b <> 0
;
도움이 되었습니까?

해결책

Logically, the select clause is one of the last parts of a query evaluated, so the aliases and derived columns are not available. (Except to order by, which logically happens last.)

Using a derived table is away around this:

select * 
from (SELECT a, b, a+b as TOTAL FROM ( 
           select 7 as a, 8 as b FROM DUAL 
           UNION ALL 
           select 8 as a, 8 as b FROM DUAL 
           UNION ALL 
           select 0 as a, 0 as b FROM DUAL) 
    )
WHERE TOTAL <> 0 
; 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top