Skip to main content

Average Distance Between Cities

MediumPremium

You are given a table with varying distances between different pairs of cities recorded by different car GPS systems. The table has the following columns:

  • origin: Name of the origin city in the pair
  • destination: Name of the destination city in the pair
  • distance: Distance between origin and destination

Write a function that calculates the average distance between each pair of cities and returns a new table with the columns city_pair and average_distance.

city_pair | average_distance ----------+------------------------ varchar | float (rounded to 2 d.p)
  • The city_pair column should contain the pair of cities in alphabetical order separated by a hyphen (e.g., “CityA-CityB”).
  • average_distance should be rounded to the nearest 2 decimal places
  • The results should be ordered according to ascending average_distance

Example

origindestinationdistance
CityACityB100
CityACityB110
CityBCityA130

Based on this table, the average distance between CityA and CityB = (100 + 110 + 130)/3 = 113.33 (round to the nearest 2 decimal places). Your solution should thus return:

city_pairaverage_distance
CityA-CityB113.33