Top 5 Most Efficient Vehicle Models
WaymoData Analyst · Technical ScreenLast updated
This problem tests your ability to aggregate data from multiple tables, calculate performance metrics, and handle common SQL pitfalls like division by zero and NULLs.
Problem Statement
You are working with a fleet database for an autonomous vehicle company. You have two tables: trips and maintenance_logs.
Tables
trips(trip_id, vehicle_id, distance_miles, fuel_consumed_gallons)maintenance_logs(log_id, vehicle_id, maintenance_cost)
Write a SQL query to identify the top 5 most efficient vehicle models. Efficiency is defined as total_miles_driven / total_fuel_consumed. Only include vehicles that have incurred at least one maintenance cost entry.
Requirements
- Calculate the efficiency for each
vehicle_id. - Handle potential division by zero errors if
total_fuel_consumedis 0 or NULL. - Return the
vehicle_idand the calculatedefficiency. - Rank the vehicles by efficiency in descending order. If two vehicles have the same efficiency, rank them by
vehicle_idin ascending order.
Constraints
distance_milesandfuel_consumed_gallonsare non-negative.- If a vehicle has no fuel consumption data, treat its efficiency as 0.
Example
Input:
trips:
| trip_id | vehicle_id | distance_miles | fuel_consumed_gallons |
|---|---|---|---|
| 1 | A1 | 100 | 5 |
| 2 | A1 | 50 | 5 |
| 3 | B2 | 200 | 0 |
maintenance_logs:
| log_id | vehicle_id | maintenance_cost |
|---|---|---|
| 101 | A1 | 500 |
Output:
| vehicle_id | efficiency |
|---|---|
| A1 | 15 |
Explanation: Vehicle A1 drove 150 miles total with 10 gallons used (150/10 = 15). Vehicle B2 is excluded because it has no maintenance log. B2 would have been excluded anyway due to division by zero protection if needed.
Hints
Hint 1
Use an INNER JOIN or an IN clause to filter for vehicles that exist in the maintenance_logs table.
Hint 2
Use SUM() with a GROUP BY clause to aggregate the total miles and total fuel per vehicle before calculating the efficiency ratio.
Hint 3
Use a CASE statement or NULLIF() to safely handle cases where the total fuel consumption might be zero to prevent query execution errors.
Follow-up questions
- How would your query change if you were asked to only consider vehicles with an above-average maintenance cost?
- What impact would adding a 'date' column have on calculating efficiency over a rolling 30-day window?
- If the 'trips' table contained millions of rows, what indexes would you suggest adding to optimize this query's performance?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.