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

Invalid column name on Having MSSQL

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
Comments