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

断了今生、忘了曾经 提交于 2019-12-10 10:58:56

问题


Here is my table named "test" - Check the snapshot here test

And then my row items: here - rowitems

I'm using the haversine formula, he is my query

  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

For some reason the HAVING or WHERE clause is not working with Distance.

It works with Latitude or Longitude.

But when I try to do WHERE Distance < 10 or HAVING Distance < 10. It says Distance is an invalid column name.

I need to be able to do this, and make a query using Distance. Any help would be appreciated.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/31211163/having-where-clause-not-working-for-haversine-formula-using-microsoft-sql

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