35. Most Frequent Travellers
A ride-sharing company wants to identify which users have traveled the most distance overall. This data can be used to reward the most frequent travellers, understand usage patterns, and improve customer retention strategies.
You're given two tables:
Users:
āāāāāāāāāāāāāāā¦āāāāāāāāāāā ā Column Name ā Type ā ā āāāāāāāāāāāāāā¬āāāāāāāāāā⣠ā id ā int ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā name ā varchar ā āāāāāāāāāāāāāāā©āāāāāāāāāāā
- user_id: Unique identifier for each user (Primary Key).
- name: The name of the user, stored as a string.
Rides:
āāāāāāāāāāāāāāā¦āāāāāāāāāāā ā Column Name ā Type ā ā āāāāāāāāāāāāāā¬āāāāāāāāāā⣠ā id ā int ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā user_id ā int ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā distance ā int ā āāāāāāāāāāāāāāā©āāāāāāāāāāā
- id: Unique ID for the ride (Primary Key).
- user_id: Refers to the id of the user who took this ride.
- distance: Distance traveled during this ride.
Write a query to find the total distance traveled by each user. Sort the result by travelled_distance in descending order. If multiple users have the same distance, sort them by name in ascending order.
Example 1:
Example:
Input:
Users:
āāāāāāāāāāāā¦āāāāāāāāāāā ā id ā name ā ā āāāāāāāāāāā¬āāāāāāāāāā⣠ā 1 ā Alice ā āāāāāāāāāāāā¼āāāāāāāāāāā ā 2 ā Bob ā āāāāāāāāāāāā¼āāāāāāāāāāā ā 3 ā Alex ā āāāāāāāāāāāā¼āāāāāāāāāāā ā 4 ā Donald ā āāāāāāāāāāāā¼āāāāāāāāāāā ā 7 ā Lee ā āāāāāāāāāāāā¼āāāāāāāāāāā ā 13 ā Jonathan ā āāāāāāāāāāāā¼āāāāāāāāāāā ā 19 ā Elvis ā āāāāāāāāāāāā©āāāāāāāāāāā
Rides:
āāāāāāāāāāāā¦āāāāāāāāāāā¦āāāāāāāāāāā ā 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 ā āāāāāāāāāāāā©āāāāāāāāāāā©āāāāāāāāāāā
Output:
āāāāāāāāāāāā¦āāāāāāāāāāāāāāāāāāāāā ā name ā travelled_distance ā ā āāāāāāāāāāā¬āāāāāāāāāāāāāāāāāāāā⣠ā Elvis ā 450 ā āāāāāāāāāāāā¼āāāāāāāāāāāāāāāāāāāāā ā Lee ā 450 ā āāāāāāāāāāāā¼āāāāāāāāāāāāāāāāāāāāā ā Bob ā 317 ā āāāāāāāāāāāā¼āāāāāāāāāāāāāāāāāāāāā ā Jonathan ā 312 ā āāāāāāāāāāāā¼āāāāāāāāāāāāāāāāāāāāā ā Alex ā 222 ā āāāāāāāāāāāā¼āāāāāāāāāāāāāāāāāāāāā ā Alice ā 120 ā āāāāāāāāāāāā¼āāāāāāāāāāāāāāāāāāāāā ā Donald ā 0 ā āāāāāāāāāāāā©āāāāāāāāāāāāāāāāāāāāā
Explanation:
- Elvis: 50 (ride ID 6) + 400 (ride ID 8) = 450
- Lee: 100 (ride ID 4) + 120 (ride ID 7) + 230 (ride ID 9) = 450
- Bob: 317 (ride ID 2) = 317
- Jonathan: 312 (ride ID 5) = 312
- Alex: 222 (ride ID 3) = 222
- Alice: 120 (ride ID 1) = 120
- Donald: No rides = 0
- Sorted by distance desc, name asc in ties.
Still unsure what the problem is asking ?
Letās go through a few more examples, step by step, to make it clearer.