简体   繁体   中英

How to fix Postgres error column does not exist?

I have the following query to postgress db

SELECT id,
       address, 
       dblong,  
       dblat,  
       111* DEGREES(ACOS(COS(RADIANS(latpoint)) * COS(RADIANS(dblat)) *  
                         COS(RADIANS(longpoint) - RADIANS(dblong)) +  
                         SIN(RADIANS(latpoint)) * SIN(RADIANS(dblat)))) AS distance_in_km 
FROM  
    (SELECT id, 
            address, 
            MAX(longitude) AS dblong,
            MAX(latitude) AS dblat  
     FROM doorbots  
     WHERE created_at > '%s' AND created_at < '%s'  
     GROUP BY 1) AS s  
JOIN 
  (SELECT %s AS latpoint, %s AS longpoint) AS p ON 1=1  
WHERE distance_in_km < %s  
GROUP BY 1;

I don't understand how to fix the following error: column "distance_in_km" does not exist ?

that should work:

with q as (
SELECT id,
       address, 
       dblong,  
       dblat,  
       111* DEGREES(ACOS(COS(RADIANS(latpoint)) * COS(RADIANS(dblat)) *  
                         COS(RADIANS(longpoint) - RADIANS(dblong)) +  
                         SIN(RADIANS(latpoint)) * SIN(RADIANS(dblat)))) AS distance_in_km 
FROM  
    (SELECT id, 
            address, 
            MAX(longitude) AS dblong,
            MAX(latitude) AS dblat  
     FROM doorbots  
     WHERE created_at > '%s' AND created_at < '%s'  
     GROUP BY 1) AS s  
JOIN 
  (SELECT %s AS latpoint, %s AS longpoint) AS p ON 1=1  
)
select * from q
WHERE distance_in_km < %s  
GROUP BY 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM