title: SQL query of Haversine formula in SQL server
body: <p>I am trying to get drivers who visited certain area from SQL server 2014 database. The table is named DriverLocationHistory.</p>
  
  <p>Here is the sql query I used : </p>
  
  <pre><code>SELECT id, ( 6371 * acos( cos( radians(37) ) * cos( radians( latitude ) ) 
  * cos( radians( Longitude ) - radians(-122) ) + sin( radians(37) ) * sin(radians(latitude)) ) ) AS distance 
  FROM DriverLocationHistory 
  HAVING distance &lt; 5 
  ORDER BY distance 
  </code></pre>
  
  <p>When I execute the query I get this error : </p>
  
  <pre><code>Msg 207, Level 16, State 1, Line 7
  Invalid column name 'distance'.
  </code></pre>