Compute Daily Distance per Vehicle From Odometer Readings
Last updated: November 29, 2026
Quick Overview
Given a table odometer_readings(vehicle_id, reading_ts, odometer_km), write SQL that returns kilometers driven per vehicle per day, ignoring negative jumps from gateway swaps or resets and physically impossible positive jumps.
Samsara
November 29, 20260
0
0 solved
Given a table odometer_readings(vehicle_id, reading_ts, odometer_km), write SQL that returns kilometers driven per vehicle per day, ignoring negative jumps from gateway swaps or resets and physically impossible positive jumps.
Mileage reports drive maintenance schedules, IFTA fuel tax filings and utilization dashboards in Samsara, and raw odometer feeds contain resets and swapped devices. The interviewer checks window functions and whether you clean data with explicit, defensible rules.
What the Interviewer Expects
- Use LAG partitioned by vehicle and ordered by time
- Compute deltas and elapsed hours between readings
- Exclude negative deltas and deltas implying impossible speed
- Aggregate by vehicle and calendar day
- Explain how deltas spanning midnight are attributed
- Count anomalies so they can be monitored
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you split a delta that spans midnight across both days?
- Which time zone should define the day for a customer with fleets in several zones?
- How would you fill a day with no readings for a utilization report?
- How would you use GPS distance to cross-check odometer distance?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
One row per reading, irregular frequency. Odometer should be monotonic per vehicle, but resets (device replaced, ECU swap, rollover) create negative deltas and occasional large positive jumps when a n...
Approach
- LAG to get the previous reading and timestamp per vehicle.
- Delta km and elapsed hours.
- Keep a delta only if it is non-negative and implies at most 150 km/h average speed (with a one minute fl...