使用计算列的 Postgresql 子查询

Postgresql subqueries using a calculated column

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

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)

我得到的错误是 错误:列“hourly_rate”不存在 第 4 行:(oil/hourly_rate)::双精度为六 ^ 提示:也许您打算引用列“production.hour_rate”。 SQL 状态:42703 字符:171 据我所知...我试过括号,命名子查询和不同的策略。我知道这是一个语法问题,有人可以帮帮我吗?谢谢

我对你的符号有点困惑,但看起来有括号问题:你的 from 语句没有链接到 select.

在我看来,管理子查询的最佳方式是这样写:

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

您不能在 select 列表中使用别名。您需要在列中包含原始计算。所以你更新的查询看起来很像 -

SELECT well_id, reported_date, oil,
       (EXTRACT(EPOCH FROM age(reported_date, LAG(reported_date) OVER w))/3600)::int as hourly_rate,
       (Oil/(EXTRACT(EPOCH FROM age(reported_date, LAG(reported_date) OVER w))/3600))::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)