Having
without Group by
does not make sense when you are not using aggregate functions on the complete expression. Having
is applied after the aggregation phase and may be used if you want to filter aggregate results.
Having ride_distance_km BETWEEN ...
will not be able to determine which row value for ride_distance_km
to consider for comparison! I believe that it is not Standard SQL, but due to (mis)feature of MySQL, it is allowed. However, there is no guarantee that it will give correct results (as explained above).
One approach would be to determine Min()
and Max()
values in a Derived Table. Then, we can utilize these aggregate values for further filtering inside the join On
clause.
Try the following query instead:
SELECT rd.ride_distance_km
FROM ride_data AS rd
JOIN
(
SELECT MIN(ride_distance_km) AS min_ride_distance,
MAX(ride_distance_km) AS max_ride_distance
FROM ride_data
) AS dt
ON rd.ride_distance_km BETWEEN 1.1*dt.min_ride_distance AND
0.9*dt.max_ride_distance