Freight Analytics: Top States, Daily Rates, and Running Totals
SQL & DataModel answerLast 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_id | load_id | driver_id | status | delivered_date | miles | payment_issued | rate_per_mile |
|---|---|---|---|---|---|---|---|
| 1 | 101 | 501 | completed | 2023-07-01 | 450 | true | 2.2 |
| 2 | 102 | 502 | cancelled | 2023-07-03 | 0 | false | 0 |
| 3 | 103 | 501 | completed | 2023-07-04 | 600 | true | 1.9 |
loads
| load_id | origin_state | destination_state | created_date |
|---|---|---|---|
| 101 | CA | TX | 2023-06-25 |
| 102 | NV | AZ | 2023-06-26 |
| 103 | OR | WA | 2023-06-27 |
drivers
| driver_id | name | hire_date | state |
|---|---|---|---|
| 501 | Alice | 2022-01-10 | CA |
| 502 | Bob | 2021-11-05 | NV |
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
DISTINCTusage 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
ROWSframing - 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).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
There are three independent deliverables. Tackle them in order and state assumptions before writing a single line.
Assumptions to state out loud
- "States in the loads table" is ambiguous because
loadshas bothorigin_stateanddestination_state. The most natural choice for a freight marketplace isorigin_state(where freight is picked up). Mention you could count both usingUNION ALLif the interviewer wants a combined view. - Status normalization. Real data often has trailing spaces or mixed casing. Wrap with
LOWER(TRIM(...))to be safe. - Ties at rank 5.
LIMIT 5with an alphabetical secondary sort is deterministic. If the interviewer wants all states that are tied for fifth, useRANK() <= 5instead. - Ties for the winner in Part 1. Break alphabetically and call it out explicitly — it shows you verified the output.
Part 1 — Top state by distinct completed jobs
Build a CTE that ranks origin states by their load count and keeps the top five. Then join jobs to loads, filter to completed jobs whose origin state falls in that set, and count distinct job IDs per state.
COUNT(DISTINCT job_id) is important even when you expect clean data. A downstream join to drivers or duplicated ingestion rows can fan out job rows silently, inflating a plain COUNT.
Part 2 — Daily average rate
Filter before grouping: status = 'completed' AND miles > 0. Cancelled and zero-mile rows carry rate_per_mile = 0, so including them pulls the average down without representing real freight economics.
If the interviewer asks for a mileage-weighted rate instead of a simple average, use SUM(rate_per_mile * miles) / NULLIF(SUM(miles), 0). The NULLIF guards against division by zero on any date where all matching jobs have zero miles.
Part 3 — Running cumulative count
The classic mistake is applying the window directly to individual job rows. With ROWS framing, two jobs on the same date receive different running totals (1 and 2) for what should be a single day's value. Aggregate to one row per date first, then apply the window. After that, ROWS and RANGE are equivalent, and you get exactly one monotonically increasing value per date.
SQL Solution (PostgreSQL)
-- Part 1: state with highest distinct completed jobs among top-5 origin states
WITH top_states AS (
SELECT origin_state
FROM loads
GROUP BY origin_state
ORDER BY COUNT(*) DESC, origin_state -- alphabetical tie-break at rank boundary
LIMIT 5
)
SELECT l.origin_state,
COUNT(DISTINCT j.job_id) AS completed_jobs
FROM jobs j
JOIN loads l ON l.load_id = j.load_id
JOIN top_states t ON t.origin_state = l.origin_state
WHERE LOWER(TRIM(j.status)) = 'completed'
GROUP BY l.origin_state
ORDER BY completed_jobs DESC, l.origin_state -- alphabetical tie-break for winner
LIMIT 1;
-- Part 2: average rate_per_mile per delivered_date (completed, non-zero miles)
SELECT delivered_date,
AVG(rate_per_mile) AS avg_rate_per_mile
FROM jobs
WHERE LOWER(TRIM(status)) = 'completed'
AND miles > 0
AND delivered_date IS NOT NULL
GROUP BY delivered_date
ORDER BY delivered_date;
-- Part 3: running cumulative count of completed jobs by delivered_date
WITH daily AS (
SELECT delivered_date,
COUNT(DISTINCT job_id) AS jobs_that_day
FROM jobs
WHERE LOWER(TRIM(status)) = 'completed'
AND delivered_date IS NOT NULL
GROUP BY delivered_date
)
SELECT delivered_date,
jobs_that_day,
SUM(jobs_that_day) OVER (
ORDER BY delivered_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS cumulative_completed_jobs
FROM daily
ORDER BY delivered_date;
Python (pandas) Equivalent
import pandas as pd
def _normalize_status(jobs: pd.DataFrame) -> pd.Series:
return jobs["status"].astype(str).str.strip().str.lower()
def _completed(jobs: pd.DataFrame) -> pd.DataFrame:
return jobs[_normalize_status(jobs) == "completed"]
# Part 1
def top_state_by_completed_jobs(
jobs: pd.DataFrame, loads: pd.DataFrame
) -> tuple[str, int] | None:
state_counts = (
loads.groupby("origin_state")
.size()
.reset_index(name="n")
.sort_values(["n", "origin_state"], ascending=[False, True])
)
top5 = set(state_counts.head(5)["origin_state"])
merged = _completed(jobs).merge(loads, on="load_id", how="inner")
merged = merged[merged["origin_state"].isin(top5)]
if merged.empty:
return None
result = (
merged.groupby("origin_state")["job_id"]
.nunique()
.reset_index(name="completed_jobs")
.sort_values(["completed_jobs", "origin_state"], ascending=[False, True])
)
row = result.iloc[0]
return row["origin_state"], int(row["completed_jobs"])
# Part 2
def avg_rate_by_date(jobs: pd.DataFrame) -> pd.DataFrame:
c = _completed(jobs)
c = c[(c["miles"] > 0) & c["delivered_date"].notna()].copy()
return (
c.groupby("delivered_date", as_index=False)["rate_per_mile"]
.mean()
.rename(columns={"rate_per_mile": "avg_rate_per_mile"})
.sort_values("delivered_date")
.reset_index(drop=True)
)
# Part 3
def cumulative_completed_by_date(jobs: pd.DataFrame) -> pd.DataFrame:
c = _completed(jobs)
c = c[c["delivered_date"].notna()]
daily = (
c.groupby("delivered_date")["job_id"]
.nunique()
.reset_index(name="jobs_that_day")
.sort_values("delivered_date")
)
# cumsum() on a sorted daily frame mirrors ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
daily["cumulative_completed_jobs"] = daily["jobs_that_day"].cumsum()
return daily.reset_index(drop=True)
Tracing Through the Sample Data
- All three origin states (CA, NV, OR) appear once, so all three are in the top five.
- Completed jobs: job 1 → CA, job 3 → OR. Job 2 is cancelled, so NV has zero.
- CA and OR tie at 1. Alphabetical tie-break → CA, 1. Calling this out explicitly shows you checked your output.
- Part 2 output: 2023-07-01 → 2.2, 2023-07-04 → 1.9. Job 2 is excluded on both counts (cancelled and zero miles).
- Part 3 cumulative: 2023-07-01 → 1, 2023-07-04 → 2.
Complexity
Let J = number of jobs, L = number of loads, S = distinct origin states, D = distinct delivered dates.
- Part 1: O(L) to group loads, O(S log S) to sort states, O(J + L) for the hash join, O(J) for the distinct count. Space O(L + J).
- Part 2: O(J) to filter and group. Space O(D).
- Part 3: O(J) to aggregate daily counts, O(D log D) to sort, O(D) for the window scan. Space O(D).
Common Mistakes
- Using
destination_stateor both columns without declaring the choice. - Skipping
DISTINCTinCOUNT, leaving the result vulnerable to join fanout. - Putting the zero-mile exclusion in
HAVINGinstead ofWHERE, which lets zero-mile rows participate in intermediate aggregation. - Applying the window to unaggregated job rows, producing multiple running-total values for the same date.
- Forgetting alphabetical tie-breaking, which makes results non-deterministic.