The Number of Times a Driver Was a Passenger SQL problem asks you to count how many times each driver has appeared as a passenger in any ride. Join the rides table to itself: once for driver IDs and once for passenger IDs, and count matches. This is a self-join aggregation problem.
Amazon asks this SQL problem to test self-join techniques — using a single table to find relationships between different roles. It validates knowledge of LEFT JOIN for preserving all drivers (even those with zero passenger appearances), GROUP BY for aggregation, and COALESCE for null handling. The database interview pattern is the core.
Self-join + GROUP BY. Join the Rides table (as drivers) with the Rides table (as passengers) on driver.driver_id = passenger.passenger_id. Group by driver_id. Count the number of passenger appearances for each driver. Use LEFT JOIN to include drivers who were never passengers (count = 0). Use COALESCE or COUNT(passenger_match) to return 0 for non-passenger drivers.
Rides: Driver A drove 3 times. Passenger A appeared 2 times. Driver B drove 2 times. Passenger B appeared 0 times. Result: Driver A → 2, Driver B → 0.
Self-join problems require aliasing the same table twice. The pattern: FROM Rides d LEFT JOIN Rides p ON d.driver_id = p.passenger_id. This finds all times each driver appeared as a passenger. LEFT JOIN preserves all drivers; COUNT(p.id) returns 0 when no passenger match exists. Practice self-join problems for "follower counts," "mutual connections," and "role overlap" analysis — they all use this aliased self-join pattern.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Customer Purchasing Behavior Analysis | Medium | Solve | |
| Employees With Deductions | Medium | Solve | |
| Find Interview Candidates | Medium | Solve | |
| Find the Missing IDs | Medium | Solve | |
| Grand Slam Titles | Medium | Solve |