You are given two tables: Users and Rides.
The Users table contains information about users with columns id (unique identifier) and name (user's name).
The Rides table contains ride information with columns id (unique identifier), user_id (foreign key referencing Users.id), and distance (distance traveled in that ride).
Task: Write a SQL query to report the total distance traveled by each user.
Requirements:
- Return results ordered by
travelled_distancein descending order - If two or more users have the same total distance, order them by
namein ascending order - Include users who haven't taken any rides (with 0 total distance)
Table Schema
| Column Name | Type | Description |
|---|---|---|
id
PK
|
int | Unique user identifier |
name
|
varchar | Name of the user |
| Column Name | Type | Description |
|---|---|---|
id
PK
|
int | Unique ride identifier |
user_id
|
int | Foreign key referencing Users.id |
distance
|
int | Distance traveled in this ride |
Input & Output
| id | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Alex |
| 4 | Donald |
| 7 | Lee |
| 13 | Jonathan |
| 19 | Elvis |
| id | user_id | distance |
|---|---|---|
| 1 | 1 | 120 |
| 2 | 2 | 317 |
| 3 | 3 | 222 |
| 4 | 7 | 100 |
| 5 | 13 | 312 |
| 6 | 19 | 50 |
| 7 | 7 | 120 |
| 8 | 19 | 400 |
| 9 | 7 | 230 |
| name | travelled_distance |
|---|---|
| Elvis | 450 |
| Lee | 450 |
| Bob | 317 |
| Jonathan | 312 |
| Alex | 222 |
| Alice | 120 |
| Donald | 0 |
Alice traveled 120 km total. Bob traveled 317 km. Alex traveled 222 km. Donald had no rides (0 km). Lee traveled 100+120+230=450 km. Jonathan traveled 312 km. Elvis traveled 50+400=450 km. Results are ordered by distance descending, with Elvis and Lee (both 450 km) ordered alphabetically by name.
| id | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| id | user_id | distance |
|---|
| name | travelled_distance |
|---|---|
| Alice | 0 |
| Bob | 0 |
When no rides exist, all users have 0 total distance and are ordered alphabetically by name since distances are equal.
Constraints
-
1 ≤ Users.id ≤ 500 -
1 ≤ Users.name.length ≤ 30 -
1 ≤ Rides.id ≤ 500 -
1 ≤ Rides.distance ≤ 2000 -
Each
user_idin Rides exists in Users table