PostgreSQL “column does not exist” error in CartoDB

爷,独闯天下 提交于 2019-12-08 07:35:47

问题


I'm currently working on a query that should return a subset of a CartoDB table (i.e. a new table) sorted by proximity to a given point. I want to display labels on the map corresponding to the closest, second closest, etc. and thought to capture that by using the PostgreSQL row_number() method in a new column:

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

However, when I try this, CartoDB/PostgreSQL returns the following error:

Error: column "dist" does not exist

Any suggestions on a better approach or something I'm missing?


回答1:


You CANT use a field calculated on the same level.

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

So you create a subquery.

SELECT dist * 1.6 as miles
FROM ( SELECT (x1-x2)^2 + (y1-x2)^2  as dist
       FROM table
     ) T



回答2:


You cannot use a column alias in another column. Here you are defining dist for result list and also use it in the row_number's ORDER BY. You have to write the same expression that you used for order instead.




回答3:


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

You can't access an alias from the same select so put it inside an inner query




回答4:


While one can use a derived inner query (which may be easier to read and can be optimized away pursuant to other RA rules), it is also possible to use ordinals to refer to columns as the restriction only applies to newly introduced names.

For example, the following is valid:

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


来源:https://stackoverflow.com/questions/35738385/postgresql-column-does-not-exist-error-in-cartodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!