The Users table lists users and the Rides table lists each ride with its distance. Report the total distance travelled by each user. Output name and travelled_distance.
Input Table(s)
Users
| Column | Type | Meaning |
|---|
| id | INT | User identifier |
| name | VARCHAR(255) | User name, never NULL, not guaranteed to be unique |
Primary key: id.
Rides
| Column | Type | Meaning |
|---|
| id | INT | Ride identifier |
| user_id | INT | User who took the ride (Users.id), never NULL |
| distance | INT | Distance of the ride, never NULL |
Primary key: id.
Output Contract
-
One row per user in
Users
, with columns
name
,
travelled_distance
, in this order.
-
travelled_distance
is the sum of
distance
over the user's rides. Users with no rides appear with
travelled_distance
=
0
.
-
Order by
travelled_distance
descending, then
name
ascending. Two rows that tie on both keys are identical, so the expected output is unique.
Example
Users
| id | name |
|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Alex |
| 4 | Bob |
| 5 | Dana |
Rides
| id | user_id | distance |
|---|
| 1 | 1 | 50 |
| 2 | 2 | 30 |
| 3 | 2 | 20 |
| 4 | 3 | 50 |
| 5 | 4 | 10 |
Expected output
| name | travelled_distance |
|---|
| Alex | 50 |
| Alice | 50 |
| Bob | 50 |
| Bob | 10 |
| Dana | 0 |
Alice, Bob (id 2) and Alex each travelled 50, so name breaks the tie. The two users named Bob are different people: id 2 travelled 30 + 20 = 50 and id 4 travelled 10. Dana has no rides and appears with 0.
Constraints and Clarifications
-
Two users can share a name. They are still different users and each gets their own row.
-
A user with no rides reports
0
, never
NULL
.
-
The output has exactly one row per row of
Users
. A ride whose
user_id
matches no user is not reported.