2014-10-10 63 views
0

我創建了兩個我想操作的僞列(取它們的百分比差異),通常可以用兩個數字字段來完成。但是我收到一個錯誤;在oracle的僞列上操作

ORA-00904: 「pseudocolumn_B」:無效的標識符

我的代碼:

select DW.mykey 
    , sum(case 
      when ms.day_date BETWEEN TO_DATE('10/09/2014', 'DD/MM/YYYY') AND TO_DATE('07/10/2014', 'DD/MM/YYYY') 
       then ms.numbers 
      else 0 
      end) pseudocolumn_A 
    , sum(case 
      when ms.day_date BETWEEN TO_DATE('03/08/2014', 'DD/MM/YYYY') AND TO_DATE('09/09/2014', 'DD/MM/YYYY') 
       then ms.numbers 
      else 0 
      end) pseudocolumn_B 
     (pseudocolumn_A - pseudocolumn_B)/pseudocolumn_B as change_in_pseudo_columns --This is the line that fails. 
from table_1 DW 
    join table_2 ms 
     on ms.mykey = DW.mykey 
    WHERE dw.some_field = 'some_value' 
group by DW.mykey 
order by DW.mykey 

我相信我已經能夠與非Oracle數據庫,因此之前做到這一點這對於Oracle來說有些不同,但我可能是錯的。我如何在上面嘗試的僞列上操作?

回答

3

不能在同一SELECT語句中使用別名列,也WHERE條款

你可以使用一個CTE和獲得所需的聚集列,然後做進一步的計算上他們像下面

with cte 
as 
(
select DW.mykey 
    , sum(case 
      when ms.day_date BETWEEN TO_DATE('10/09/2014', 'DD/MM/YYYY') AND TO_DATE('07/10/2014', 'DD/MM/YYYY') 
       then ms.numbers 
      else 0 
      end) psuedocolumn_A 
    , sum(case 
      when ms.day_date BETWEEN TO_DATE('03/08/2014', 'DD/MM/YYYY') AND TO_DATE('09/09/2014', 'DD/MM/YYYY') 
       then ms.numbers 
      else 0 
      end) psuedocolumn_B 
from table_1 DW 
    join table_2 ms 
     on ms.mykey = DW.mykey 
    WHERE dw.some_field = 'some_value' 
group by DW.mykey 
) 
select * , 
     (psuedocolumn_A - psuedocolumn_B)/psuedocolumn_B 
from cte 
order by cte.mykey 
+0

CTE在內部被解析爲內聯視圖或臨時表,因此基本上它是一個子查詢,當您想要避免多個子查詢時它很有用。在OP的情況下,子查詢只使用一次。所以CTE不會有什麼顯着的區別。 – 2014-10-10 19:05:54

+2

@LalitKumarB,是的,你是對的,子查詢就夠了,ithink cte幾乎不可讀。 – radar 2014-10-10 19:09:16

1

不能將列別名用作同一查詢中的列名稱。用它作爲子查詢。

把下面,psuedocolumn_A - psuedocolumn_B)/psuedocolumn_B as change_in_psuedo_columns作爲外部查詢:

select psuedocolumn_A - psuedocolumn_B)/psuedocolumn_B as change_in_psuedo_columns 
from (your query in original post) 

或者,即使是INLINE VIEW就足夠了。