Irmantas Medeišis Irmantas Medeišis - 6 months ago 18
SQL Question

Invalid column name on Having in SQL Server

I have quick question why I can't use having keyword on distance? I need somehow to check is distance < 20 for example

SELECT
Id, Lat, Lng,
(6367 * acos( cos( radians(45.444) )
* cos( radians( Lat ) ) * cos( radians( Lng ) - radians(158.554) )
+ sin( radians(4545) ) * sin( radians( Lat ) ) ) ) AS distance
FROM
Posts
HAVING
distance < 15 // Invalid column Name
ORDER BY
distance

Answer

Try this

SELECT * 
FROM
    (SELECT 
         Id, Lat, Lng,
         (6367 * acos(cos(radians(45.444)) * cos(radians(Lat)) * 
          cos(radians(Lng) - radians(158.554)) + sin(radians(4545)) * 
          sin(radians(Lat)))) AS distance 
     FROM Posts) p
WHERE 
    p.distance < 15  
ORDER BY 
    p.distance