CartoDB 中的 PostgreSQL "column does not exist" 错误

PostgreSQL "column does not exist" error in CartoDB

我目前正在处理一个查询,该查询应该 return CartoDB table 的 子集 (即新的 table)按与给定点的接近程度排序。我想在地图上显示与最近、第二最近等相对应的标签,并想通过在新列中使用 PostgreSQL row_number() 方法来捕获它:

SELECT
    *,
    ST_Distance(
        ST_GeomFromText('Point(-73.95623080000001 40.6738101)', 4326)::geography,
        the_geom::geography
    ) / 1609 AS dist,
    row_number() OVER (ORDER BY dist) as rownum
FROM locations
WHERE ST_Intersects(
   ST_GeomFromText(
      'Point(-73.95623080000001 40.6738101)', 4326
   ),
   the_geom
)
ORDER BY dist ASC

但是,当我尝试这样做时,CartoDB/PostgreSQL return出现以下错误:

Error: column "dist" does not exist

关于更好的方法或我遗漏的东西有什么建议吗?

您不能在另一列中使用列别名。在这里,您为结果列表定义了 dist,并且还在 row_numberORDER BY 中使用了它。您必须改写用于 order 的相同表达式。

不能使用在同一级别计算的字段。

SELECT (x1-x2)^2 + (y1-x2)^2  as dist, dist * 1.6 as miles
                                       ^^^^^
                                    undefined

所以你创建了一个子查询。

SELECT dist * 1.6 as miles
FROM ( SELECT (x1-x2)^2 + (y1-x2)^2  as dist
       FROM table
     ) T
SELECT *,
    row_number() OVER (ORDER BY dist) as rownum
FROM(
SELECT
    *,
    ST_Distance(
        ST_GeomFromText('Point(-73.95623080000001 40.6738101)', 4326)::geography,
        the_geom::geography
    ) / 1609 AS dist
FROM locations
WHERE ST_Intersects(
   ST_GeomFromText(
      'Point(-73.95623080000001 40.6738101)', 4326
   ),
   the_geom
)
) i
ORDER BY dist ASC

您无法从同一个 select 访问别名,因此请将其放在内部查询中

虽然可以使用派生的内部查询(它可能更容易阅读并且可以根据其他 RA 规则进行优化),但也可以使用 ordinals 来请参考列,因为限制仅适用于新引入的 names.

例如,以下是有效的:

SELECT
    ST_Distance(
        ST_GeomFromText('Point(-73.95623080000001 40.6738101)', 4326)::geography,
        the_geom::geography
    ) / 1609 AS dist
  -- column ordering changed to make ordinal obvious, as * can bite
  -- now column 'dist' is the first column and can be referenced by ordinal
  , row_number() OVER (ORDER BY 1) as rownum
  , *
FROM locations
WHERE ST_Intersects(
   ST_GeomFromText(
      'Point(-73.95623080000001 40.6738101)', 4326
   ),
   the_geom
)
-- this could also be written as ORDER BY 1 ASC, per ordinal
ORDER BY dist ASC