This is a really interesting problem I have been struggling with all day. I have a table with an ID, Latitude, and Longitude of a location. This is a subset of locations from a larger set of locations.
What I am trying to do is use this subset of locations and, for each location, return locations within 20 miles from the larger set using air distance. My issue is not with calculating the air distances, that is working, my issue is with how to operate on each row like a For
loop but with a set-based method.
So let's say this is my subset table, LocationSubset
+----+---------+----------+
| ID | Lat | Lon |
+----+---------+----------+
| 1 | 41.0575 | -92.1364 |
+----+---------+----------+
| 2 | 47.0254 | -92.5723 |
+----+---------+----------+
| 3 | 38.9897 | -88.7623 |
+----+---------+----------+
And I am looking towards the larger table, Locations
+----+---------+-----------+
| ID | Lat | Lon |
+----+---------+-----------+
| 1 | 41.0575 | -92.1364 |
+----+---------+-----------+
| 2 | 47.0254 | -92.5723 |
+----+---------+-----------+
| 2 | 38.9897 | -88.7623 |
+----+---------+-----------+
| 4 | 36.2137 | -91.6528 |
+----+---------+-----------+
| 5 | 39.2643 | -123.0073 |
+----+---------+-----------+
| 6 | 39.941 | -123.0073 |
+----+---------+-----------+
| 7 | 35.7683 | -91.6528 |
+----+---------+-----------+
| 8 | 45.8406 | -91.6528 |
+----+---------+-----------+
Let's assume, using the Haversine formula that locations 5 and 6 are within 20 miles of location 1 and locations 4 and 8 are within 20 miles of location 2.
I am looking to return something like this:
+----+------------+----------+
| ID | LocationID | Distance |
+----+------------+----------+
| 1 | 5 | 15.4 |
+----+------------+----------+
| 1 | 6 | 16 |
+----+------------+----------+
| 2 | 4 | 17.4 |
+----+------------+----------+
| 2 | 8 | 2.5 |
+----+------------+----------+
Each location could have zero to many locations within 20 miles and I am trying to capture this in another table.
I can add clarification if necessary. Thank you for your time.