SQL - Manhattan Distance
- Manhattan Distance : total distance = | c - a | + | d - b |
My first answer
SELECT round(Max(LONG_W)-MIN(LONG_W)+MAX(LAT_N)-MIN(LAT_N),4)
from station;While this works, it looks messy. I wonder if I can get a result using substitution.
SELECT round(A + B,4)
from(
SELECT
Max(LONG_W)-MIN(LONG_W) AS A,
MAX(LAT_N)-MIN(LAT_N) AS B
from station
) AS tmpI defined the coordinate differences as A and B beforehand. It works well and looks like more readable.
If we want to use Euclidean Distance instead of Manhattan Distance, we can apply the geometric formula that √(A² + B²)
Get Minseo Kim’s stories in your inbox
Join Medium for free to get updates from this writer.
Thanks to the substitution structure we built earlier, we don’t need to rewrite the entire subquery. We can easily calculate it by adding SQL’s SQRT() and POW() functions to the main query
SELECT round(SQRT(POW(A,2) + POW(B, 2)) ,4)
from(
SELECT
Max(LONG_W)-MIN(LONG_W) AS A,
MAX(LAT_N)-MIN(LAT_N) AS B
from station
) AS tmp







