vbaid
vbaid

Reputation: 89

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

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.

Upvotes: 2

Views: 369

Answers (2)

SQL Police
SQL Police

Reputation: 4196

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.

Upvotes: 1

ericpap
ericpap

Reputation: 2937

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

Upvotes: 2

Related Questions