PostgreSQL"列不存在" CartoDB中的错误

时间:2016-03-02 04:14:53

标签: sql postgresql postgis cartodb

我正在处理一个查询,该查询应该返回按给定点的距离排序的CartoDB表(即新表)的子集。我想在地图上显示与最近,第二近等对应的标签,并考虑通过在新列中使用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会返回以下错误:

Error: column "dist" does not exist

有关更好的方法或我遗漏的任何建议吗?

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

您不能在另一列中使用列别名。您可以在此处为结果列表定义dist,并在row_number' s ORDER BY中使用它。您必须编写用于order的相同表达式。

答案 2 :(得分:1)

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

您无法从同一个选择中访问别名,因此请将其置于内部查询

答案 3 :(得分:1)

虽然可以使用派生的内部查询(可能更容易阅读并且可以根据其他RA规则进行优化),但也可以使用序数将列称为限制仅适用于新引入的名称

例如,以下内容有效:

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