Search code examples
sqlsql-servergoogle-mapsgpslatitude-longitude

Query Error with Having Clause using computed column


I am trying to find nearest locations based on latitude and longitude by using the locations in my database. Here is my query:

select *,
acos(cos(33.7103820972222 * (PI()/180)) *
 cos(73.05794 * (PI()/180)) *
 cos(Lat * (PI()/180)) *
 cos(Lon * (PI()/180))
 +
 cos(33.7103820972222 * (PI()/180)) *
 sin(73.05794 * (PI()/180)) *
 cos(Lat * (PI()/180)) *
 sin(Lon * (PI()/180))
 +
 sin(33.7103820972222 * (PI()/180)) *
 sin(73.05794 * (PI()/180))
) * 3959 AS Dist from tblOrg having Dist < 5 order by Dist

I am having error in Dist in the below line having Dist < 5.


Solution

  • As marc_s commented "HAVING should only be used with conditions that include an aggregate function like SUM, COUNT etc. - otherwise, if you don't have any aggregate in your condition, use WHERE instead"

    And you can't access a computed column directly in a having or where clause. So instead make a sub-query:

    select *
    from (
      select *,
        acos(cos(33.7103820972222 * (PI()/180)) *
        cos(73.05794 * (PI()/180)) *
        cos(Lat * (PI()/180)) *
        cos(Lon * (PI()/180))
        +
        cos(33.7103820972222 * (PI()/180)) *
        sin(73.05794 * (PI()/180)) *
        cos(Lat * (PI()/180)) *
        sin(Lon * (PI()/180))
        +
        sin(33.7103820972222 * (PI()/180)) *
        sin(73.05794 * (PI()/180))
        ) * 3959 AS Dist
      from tblOrg
    ) x
    where Dist < 5
    order by Dist