Having/Where clause not working for Haversine Formula using Microsoft SQL

孤街浪徒 提交于 2019-12-06 11:37:58

You cannot use calculated fields on a where or having clause. Create a view or use a subquery

Try this:

select * FROM (SELECT *, ( 3960 * acos( cos( radians( 33.650800 ) ) *
cos( radians( Latitude ) ) * cos( radians(  Longitude  ) - radians( -117.891729 ) ) +
sin( radians( 33.650800 ) ) * sin( radians(  Latitude  ) ) ) ) AS Distance 
FROM test) as T WHERE T.Distance < 10

You need to put your query into a subquery, or a view, or a CTE (common table expression).

Here is an example for your task with a CTE:

WITH cte_test (Name, Latitude, Longitude, Distance)
AS 
(
    SELECT Name, Latitude, Longitude, 
         3960 * acos(cos(radians(33.650800)) 
         * cos(radians( Latitude ) )  
         * cos( radians(  Longitude  ) - radians( -117.891729 ) ) 
         + sin( radians( 33.650800 ) ) * sin( radians(  Latitude  ) ) ) ) 
         AS Distance 
    FROM test
)
SELECT * from cte_test where Distance < 10 ;

A CTE is a kind of "temporary view". It is also a powerful instrument which can also be used for creating recursive queries.

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