You're building a ride-sharing analytics dashboard and need to calculate the total distance traveled by each user in your system.
You have two tables:
- Users table: Contains user information (user_id, name)
- Rides table: Contains ride records (ride_id, user_id, distance)
Your task is to write a SQL query that returns each user's user_id, name, and total_traveled_distance. Here's the catch: some users might not have taken any rides yet, so their total distance should be 0.
The results should be ordered by user_id in ascending order.
Example:
If Alice (user_id=1) took 3 rides covering 10, 15, and 20 miles, her total should be 45 miles. If Bob (user_id=2) hasn't taken any rides, his total should be 0.
Input & Output
Visualization
Time & Space Complexity
Single pass through users (n) and rides (m) tables, plus sorting
Space for the result set containing all users
Constraints
- 1 โค Users.user_id โค 106
- 1 โค Rides.ride_id โค 106
- 1 โค Rides.distance โค 1000
- All user_id values in Users table are unique
- All ride_id values in Rides table are unique
- user_id in Rides table references valid users in Users table