Skip to content

How many drivers in the same city rate higher

HardFull bankSelf joinsRanking and top NCTEs and subqueries25 min3 hidden datasets

The task

Driver operations wants each driver's standing in their home city: how many other drivers there have a better average rating.

Rules:

  • A driver's rating is the average of rider_rating over their completed trips that were rated (rider_rating is not NULL). Unrated trips are ignored.
  • Only drivers with at least 10 rated completed trips take part, both as the driver being described and as someone being compared against.
  • A driver's city is drivers.city_id, not the city of the trip.
  • higher_rated_drivers counts the participating drivers in the same city whose exact average is strictly higher. Drivers with equal averages do not count against each other.

Return driver_id, city_id, avg_rating (the driver's average, rounded to 2 decimal places, for display only) and higher_rated_drivers. Sort by city_id, then higher_rated_drivers, then driver_id.

Expected output

driver_idcity_idavg_ratinghigher_rated_drivers
  • Sorted by city_id ascending, then higher_rated_drivers ascending, then driver_id ascending.
  • Numbers rounded to 2 decimal places.
  • Checked on the sample and on 3 hidden datasets. How grading works

Tables Ride-hailing marketplace · click a name to insert it

cities4 rows in the sample

Cities we operate in. Key: city_id.

intUnique id.
textName.
textTwo-letter country code.
drivers60 rows in the sample

One row per driver. Key: driver_id.

intUnique id.
textName.
intHome city.
dateFirst day driving.
textstandard, xl or electric.
riders220 rows in the sample

One row per rider. Key: rider_id.

intUnique id.
textName.
dateSign-up day.
trips1,800 rows in the sample

One row per ride request. Key: trip_id.

intUnique id.
intWho asked.
intDriver who accepted. NULL when nobody did.
intWhere.
timestampRequest time (UTC).
timestampPickup time. NULL if never picked up.
timestampDrop-off time. NULL unless completed.
textcompleted, rider_cancelled, driver_cancelled or no_driver.
numeric(10,2)Fare in local currency units. NULL unless completed.
numeric(6,2)Trip distance. NULL unless completed.
intRider's rating of the driver, 1 to 5. NULL if not rated.

Related questions

Loading the editor and PostgreSQL