在oracle中的伪列上运行

时间:2014-10-10 18:53:49

标签: sql 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来说有些不同,但我可能错了。如何按上述方法操作伪列?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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也足够了。