I have sql query like shown below the sql server says that their is error in HAVING and ORDER bY is their any error with syntax near HAVING and ORDER BY, can anyone help.
SELECT Id,
Name1,
ZipCode,
StreetName,
StreetNumber,
State1,
Lat,
Lng,
Keyword,
( 6371 * ACOS( COS( (12.925432/57.2958) ) * COS( (Lat/57.2958) ) * COS( ( Lng/57.2958 ) - (77.5940171/57.2958) ) + SIN( 12.925432/57.2958 ) * SIN( Lat/57.2958 ) ) ) AS distance
FROM Business_Details
HAVING (distance < 1.5) and (Keyword like '%plumber%')
ORDER BY distance ;
Everyone has already mentioned that HAVING is for aggregate data, like SUM and MIN and you can put those two conditions in your WHERE clause.
For what it's worth (I cannot test right now) and to hopefully address your actual question, it has been my experience that you can not use a column alias in the HAVING clause, and must explicitly rewrite the equation for the column there instead of the alias.
See this question for more details.
Use
where
here instead ofhaving
.having
is useful for narrowing conditions on aggregate values.where
is useful for narrowing conditions on un-aggregated data.Update
SQL Server is not MySQL, what works on one ...
This should be what you need
HAVING is generally used in conjunction with a GROUP BY statement. HAVING is like the WHERE for the resulting groups.