在其他列中引用postgresql查询列

时间:2012-06-26 11:01:03

标签: sql postgresql

鉴于我有一些数据表...我有一个查询,用于检索具有复杂案例子句的数据...

 SELECT row_number() over (...) as num, ... as field 1, 
    case ... as field2 
    FROM ...

现在我想添加更复杂的逻辑,比如

 SELECT row_number() over (...) as num, ... as field 1, 
    field2 * num as field2 
    FROM ...

基本上,如果我输入row_num + 1 as field2 Postgres会给我回复

错误:列“row_num”不存在

如何在此查询中引用查询字段?

2 个答案:

答案 0 :(得分:6)

制作外表并在该表中选择字段2

Select *, num+1 as field2
from
(
   SELECT row_number() over (...) as num, ... as field1 FROM ...
) t

答案 1 :(得分:0)

SELECT row_number() over (...) as num,
       1 + row_number() over (...) as field2,
       ... as field3,
  FROM ...