Instagram
youtube
Facebook
Twitter

Manhattan Distance Calculation SQL Query

Consider  and  to be two points on a 2D plane.

  •  happens to equal the minimum value in Northern Latitude (LAT_N in STATION).
  •  happens to equal the minimum value in Western Longitude (LONG_W in STATION).
  •  happens to equal the maximum value in Northern Latitude (LAT_N in STATION).
  •  happens to equal the maximum value in Western Longitude (LONG_W in STATION).

Query the Manhattan Distance between points  and  and round it to a scale of  decimal places.

Input Format

The STATION table is described as follows:

where LAT_N is the northern latitude and LONG_W is the western longitude.

Solution:

select ROUND(ABS(MAX(LAT_N) - MIN(LAT_N)) + ABS(MAX(LONG_W) - MIN(LONG_W)), 4) 
FROM STATION;

Explanation:

  • The query is selecting a single value, which is the result of an arithmetic expression involving the latitude (LAT_N) and longitude (LONG_W) coordinates.
  • MAX(LAT_N) - MIN(LAT_N): This calculates the difference between the maximum and minimum values of the LAT_N column. This gives the range (span) of latitude values in the table.
  • MAX(LONG_W) - MIN(LONG_W): Similarly, this calculates the difference between the maximum and minimum values of the LONG_W column. This gives the range (span) of longitude values in the table.
  • ABS(MAX(LAT_N) - MIN(LAT_N)) + ABS(MAX(LONG_W) - MIN(LONG_W)): This adds the absolute differences calculated for latitude and longitude. This represents a combined range of the geographical coordinates.
  • ROUND(..., 4): The ROUND function rounds the result to 4 decimal places. This ensures the final result is presented with a precision of four decimal places.