Top three drivers per city

hardSQL~30 min · 4 tests · ridelog

Each city manager wants a podium: their three highest-earning drivers, and how much of the city’s money each one brought in.

Use only trips with status = 'completed'. A driver’s earnings in a city are the sum of fare over their completed trips in that city (use trips.city). The city total is the sum of fare over every completed trip in that city.

Rank drivers inside each city by earnings, highest first, with ties sharing a rank and the next rank skipping (1, 2, 2, 4). Keep every driver whose rank is 3 or better. A tie for third place keeps both drivers, so a city can return more than three rows. A city with fewer than three drivers returns all of them.

Return:

column type meaning
city text the city
driver_rank integer rank inside the city, 1 = top earner
driver_id integer the driver
earnings decimal the driver’s completed fares in that city, rounded to 2 decimals
city_share_pct decimal earnings / city total * 100, rounded to 1 decimal

Order matters: by city, then driver_rank, then driver_id.

Tables: trips.

Learn the ideaRead the lesson →
solution.sqlDuckDB · ridelog

Press ⌘ ↵ or Run to check the visible tests. Submit runs the hidden ones too. Everything runs in your browser.

⌘ ↵ to run