postgresql - 列不存在(在查询中创建列)

标签 postgresql

运行此查询时,我在 postgres 的 SELECT 部分收到错误“列“距离”不存在”。 “距离”是指给定坐标的两点之间的距离。我怀疑这是一个时间问题?该函数在错误发生之前已正确创建。

CREATE OR REPLACE FUNCTION pg_temp.earthDistance(lat1 double precision, lng1 double precision, lat2 double precision, lng2 double precision)
  RETURNS double precision AS
$BODY$
SELECT 
  asin(
  sqrt(
    sin(radians($3-$1)/2)^2 +
    sin(radians($4-$2)/2)^2 *
    cos(radians($1)) *
    cos(radians($3))
  )
  ) * 7918 AS distance;
$BODY$
  LANGUAGE sql IMMUTABLE;

SELECT populated_place.name AS populated_place_name, 
  feature.name AS feature_name, 
  ROUND(
    pg_temp.earthDistance(
      populated_place.latitude,
      populated_place.longitude,
      feature.latitude,
      feature.longitude)::NUMERIC,
  2) AS distance,
  RANK() OVER (PARTITION BY populated_place_name ORDER BY distance) AS rank
FROM populated_place JOIN feature ON
  feature.type='summit' AND
  populated_place.population>=100000
WHERE distance<=200
ORDER BY populated_place_name, rank;

最佳答案

您不能在 WHERE 子句中使用别名(distance)。使用派生表:

SELECT 
    *, 
    RANK() OVER (PARTITION BY populated_place_name ORDER BY distance) AS rank
FROM (  
    SELECT 
        populated_place.name AS populated_place_name, 
        feature.name AS feature_name, 
        ROUND(
            pg_temp.earthDistance(
            populated_place.latitude,
            populated_place.longitude,
            feature.latitude,
            feature.longitude)::NUMERIC, 2) AS distance
    FROM populated_place 
    JOIN feature ON
        feature.type='summit' AND
        populated_place.population>=100000
    ) sub
WHERE distance <= 200
ORDER BY populated_place_name, rank;

另请参阅:Using an Alias in a WHERE clause .

关于postgresql - 列不存在(在查询中创建列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33720323/

相关文章:

sql - Postgres/Redshift : Extract Quarter and Year from date column for a group by in one call?

sql - 如何在 sql 层次结构上显示祖 parent ?

sql - PostgreSQL:如何更新表中的日期?

SQL:高效计算花费的时间

sql - 改变列(使用 + where)

postgresql - Postgres 查询的性能

postgresql - 有多次通过 : How to select records with no relation OR by some condition in relation?

bash - catch a psql(PostgreSQL) command error in bash, that can be used generic, indifferent of the sql

sql - 如何编写 SQL 以在满足条件时返回一行,否则返回另一行

sql - 提高PostgreSQL集差效率