Skip to main content
All Questions

Calculate the average distance between cities.

Medium
Unlock detailed company stats for this questionUpgrade

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

Related courses

Course

Data Science Interview Prep

Land your dream data science role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice statistics, experimentation, coding, SQL, machine learning, behavioral interviews, and more.

Course

SQL Interviews

Prepare for SQL interviews by practicing syntax basics, aggregations, and window functions. Learn how to manipulate data, write complex queries, and analyze information from diverse data sets.