SQL
Lab
Uber Uber Interview Question 05

Driver
Earnings
Ranking

Rank drivers by total earnings within each city.

Table Schema

Inspect
Table

interactive
ColumnType
trip_idinteger
driver_idinteger
cityvarchar
faredecimal

Sample Data

Input
Output

Sample Input: trips
trip_iddriver_idcityfare
1201NYC20
2202NYC30
3201NYC25
4203SF40
5204SF35
6203SF20
Expected Output
driver_idcityrank
201NYC1
202NYC2
203SF1
204SF2

SQL Editor

Run
Query

postgresql
Waiting for query

driver_idcityrank
201NYC1
202NYC2
203SF1
204SF2

Hints

Unlock
Clues

Hint 01: Identify the grouping level required by the output.
Hint 02: Aggregate with COUNT, SUM, AVG, or a window function as needed.
Hint 03: Filter after aggregation with HAVING or after ranking with an outer query.

Solution

Locked
Answer

Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.

WITH earnings AS (
  SELECT driver_id, city, SUM(fare) AS total_earnings
  FROM trips
  GROUP BY driver_id, city
)
SELECT driver_id, city, RANK() OVER (PARTITION BY city ORDER BY total_earnings DESC) AS rank
FROM earnings;

Explanation

Step By
Step

01

Read the expected output columns to determine the final grain.

02

Aggregate or rank the input rows to calculate the requested metric.

03

Filter, sort, and alias the final columns to match the output.

Related Questions

Keep
Solving