Table Schema
Inspect
Table
| Column | Type |
|---|---|
| trip_id | integer |
| driver_id | integer |
| city | varchar |
| fare | decimal |
Rank drivers by total earnings within each city.
Table Schema
| Column | Type |
|---|---|
| trip_id | integer |
| driver_id | integer |
| city | varchar |
| fare | decimal |
Sample Data
| trip_id | driver_id | city | fare |
|---|---|---|---|
| 1 | 201 | NYC | 20 |
| 2 | 202 | NYC | 30 |
| 3 | 201 | NYC | 25 |
| 4 | 203 | SF | 40 |
| 5 | 204 | SF | 35 |
| 6 | 203 | SF | 20 |
| driver_id | city | rank |
|---|---|---|
| 201 | NYC | 1 |
| 202 | NYC | 2 |
| 203 | SF | 1 |
| 204 | SF | 2 |
SQL Editor
| driver_id | city | rank |
|---|---|---|
| 201 | NYC | 1 |
| 202 | NYC | 2 |
| 203 | SF | 1 |
| 204 | SF | 2 |
Hints
Solution
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
Read the expected output columns to determine the final grain.
Aggregate or rank the input rows to calculate the requested metric.
Filter, sort, and alias the final columns to match the output.
Related Questions