首页 > 解决方案 > 使用计算列的 Postgresql 子查询

问题描述

我是这个平台的新手,需要使用我已经计算过的列来获取值。我知道我需要一个子查询,但对正确的语法感到困惑。

SELECT well_id, reported_date, oil,
  (EXTRACT(EPOCH FROM age(reported_date,
                          LAG(reported_date) OVER w))/3600)::int as hourly_rate,
                         (oil/hourly_rate)::double precision as six
                          FROM public.production
WINDOW w AS (PARTITION BY well_id ORDER BY well_id, reported_date 
             ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)

我得到的错误是 ERROR: column "hourly_rate" does not exist LINE 4: (oil/hourly_rate)::double precision as 6 ^ HINT: 也许你的意思是引用列“production.hour_rate”。SQL 状态:42703 字符:171 我明白...我尝试过括号,命名子查询和不同的策略。我知道这是一个语法问题,有人可以帮我一把。谢谢

标签: postgresqlsubquery

解决方案


我对你的符号有点困惑,但看起来有括号问题:你的from陈述没有链接到选择。

在我看来,管理子查询的最好方法是写这样的东西:

WITH query1 AS (
   select col1, col2
      from table1
),
query2 as (
   select col1, col2
      from query1
   (additional clauses)
),
select (what you want)
 from query2
(additional statements)

Then you can manipulate your data progressively until you have the right organisation of your data for the final select, including aggregations

推荐阅读