SQL query - Group by an approximation
I have a query: SELECT ID, Name开发者_如何学Python, Distance FROM Station GROUP BY 'Distance approximation'
In my example, Distance is a double and I would like to group all the elements with the same approximate distance together. For example, element_1 with distance 212 will be in the same group as element_2 with distance 240 but not in the same group as 300 (difference is > 50).
Thanks
Depending on your database, you can group by a function.
So you could do something like (very simple)
select round(distance/50) as approximate_distance, count(*)
from station
group by round(distance/50)
You can add in your own functions based on your requirements.
One way to do it is to divide the distance by 50 make it an integer and group by that result.
Something like this: (not tested)
SELECT floor(Distance/50) as [group], count(*) as count
FROM Station
GROUP BY floor(Distance/50)
The one drawback of this way is that two numbers close to each other could still be in different groups. For example distance of 249 would be in a different group than 251.
Since any such grouping would require some boundary points, you need to be clear about your requirements -- then an algorithm can be designed.
精彩评论