KatInterview

Freight Analytics: Top States, Daily Rates, and Running Totals

SQL & DataModel answer
MediumModel answerSQL & Datawindow-functionsaggregationjoins

Last updated

Join three logistics tables to rank states by completed jobs, compute daily average rates, and build a running cumulative count using window functions.

Freight Analytics: Top States, Daily Rates, and Running Totals

You are working with a freight dispatch platform. Three tables capture the core operational data:

jobs

job_idload_iddriver_idstatusdelivered_datemilespayment_issuedrate_per_mile
1101501completed2023-07-01450true2.2
2102502cancelled2023-07-030false0
3103501completed2023-07-04600true1.9

loads

load_idorigin_statedestination_statecreated_date
101CATX2023-06-25
102NVAZ2023-06-26
103ORWA2023-06-27

drivers

driver_idnamehire_datestate
501Alice2022-01-10CA
502Bob2021-11-05NV

Your Task

Write SQL (or equivalent pandas code) to answer the following three parts. Treat them as a single deliverable: state your assumptions, then produce the queries.

Part 1 — Top state by completed jobs

Identify the five origin states with the most load records in the loads table. Among those five states, find the one with the highest count of distinct completed jobs. Return the state name and the job count. If two states tie, break the tie alphabetically.

Part 2 — Daily average rate

For completed jobs only, compute the average rate_per_mile for each delivered_date. Exclude any row where miles = 0. Return one row per date, ordered chronologically.

Part 3 — Running cumulative job count

Produce a day-by-day running total of completed jobs ordered by delivered_date. Use a window function with explicit ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW framing. Return the date, the count for that day, and the cumulative count.


What interviewers look for

  • Correct join strategy and DISTINCT usage that is robust to duplicate rows
  • Proper pre-filtering before aggregation (zero-mile exclusion, status normalization)
  • Understanding why pre-aggregating to one row per date matters for ROWS framing
  • Awareness of tie-breaking and ambiguous column choices

Hints

Hint 1

For Part 1, decide upfront whether 'states in the loads table' means origin_state, destination_state, or both combined with UNION ALL — state your choice before writing code. Then use a CTE to isolate the top five before joining to jobs.

Hint 2

For Part 2, the WHERE clause must filter out both cancelled jobs and zero-mile rows before GROUP BY, not after. A HAVING clause on AVG won't give you the same result if zero-mile completed jobs exist.

Hint 3

For Part 3, applying the window function directly to individual job rows causes jobs on the same date to receive different running totals. Collapse to one row per delivered_date first, then apply SUM() OVER (ORDER BY delivered_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW).