1

我目前正在处理一个查询,该查询应返回按与给定点的接近程度排序的 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

4 回答 4

2

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

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
于 2016-03-02T04:21:31.310 回答
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
于 2016-03-02T04:38:21.810 回答
1

您不能在另一列中使用列别名。在这里,您正在定义dist结果列表并在row_number's中使用它ORDER BY。您必须编写与以前相同的表达式order

于 2016-03-02T04:19:12.717 回答
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

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

于 2016-03-02T04:27:26.117 回答