Freight Origin Leaders, Daily Haul Rates, and Running Job Totals
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
Write three analytical SQLite queries (TOP_STATE_QUERY, AVG_RATE_QUERY, and CUMULATIVE_QUERY) over a freight brokerage database containing three tables:
jobs:(job_id INTEGER, load_id INTEGER, driver_id INTEGER, status VARCHAR, delivered_date DATE, miles INTEGER, payment_issued BOOLEAN, rate_per_mile DECIMAL(10,2))loads:(load_id INTEGER, origin_state VARCHAR, destination_state VARCHAR, created_date DATE)drivers:(driver_id INTEGER, name VARCHAR, hire_date DATE, state VARCHAR)
Each job belongs to the pickup state recorded in loads.origin_state via jobs.load_id = loads.load_id, and a finished haul is identified by exact match status = 'completed'.
Implement all three SQL queries in starter.py:
-
TOP_STATE_QUERY— Completed-job leader among top-5 pickup states:- Rank non-null
loads.origin_statevalues by their number of distinctload_ids descending, breaking ties alphabetically (origin_state ASC), and keep at most5states. - Among that shortlist of up to
5pickup states, count each state's distinct completedjob_ids (jobs.status = 'completed'). A shortlisted state with zero completed jobs must remain eligible with count0. - Output a single row
(state, completed_jobs)for the shortlisted state with the highestcompleted_jobscount (breaking ties alphabetically bystate ASC), or zero rows ifloadshas no non-nullorigin_state.
- Rank non-null
-
AVG_RATE_QUERY— Daily unweighted and mile-weighted haul rates:- Filter
jobsto rows wherestatus = 'completed',milesis non-null andmiles <> 0,rate_per_mile IS NOT NULL, anddelivered_date IS NOT NULL. - Group by
delivered_dateand return(delivered_date, avg_rate_per_mile, weighted_rate_per_mile)ordered bydelivered_dateascending, where:avg_rate_per_mileis the plain arithmetic mean ofrate_per_mileon that date, andweighted_rate_per_mileisSUM(rate_per_mile * miles) / SUM(miles)computed with real floating-point division.
- Filter
-
CUMULATIVE_QUERY— Daily and running completed job counts:- Filter
jobsto rows wherestatus = 'completed'anddelivered_date IS NOT NULL(completed jobs withmiles = 0are counted here). - Return one row per
delivered_datein ascending order with columns(delivered_date, completed_jobs, cumulative_completed_jobs), wherecompleted_jobsis the count of distinctjob_ids completed on that date andcumulative_completed_jobsis the running sum across ordered date rows using a window function (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW).
- Filter
Examples
Example 1
Input:
loads:
load_id | origin_state | destination_state | created_date
--------+--------------+-------------------+-------------
201 | IL | OH | 2024-03-01
202 | IL | MI | 2024-03-02
203 | GA | FL | 2024-03-02
204 | CO | UT | 2024-03-03
jobs:
job_id | load_id | driver_id | status | delivered_date | miles | payment_issued | rate_per_mile
-------+---------+-----------+-----------+----------------+-------+----------------+--------------
11 | 201 | 701 | completed | 2024-03-05 | 200 | true | 2.50
12 | 203 | 702 | completed | 2024-03-05 | 600 | true | 2.10
13 | 202 | 701 | cancelled | 2024-03-06 | 0 | false | 0.00
14 | 202 | 701 | completed | 2024-03-08 | 300 | true | 2.40
15 | 204 | 703 | completed | 2024-03-08 | 0 | true | 0.00
drivers:
driver_id | name | hire_date | state
----------+--------+------------+------
701 | Elena | 2022-05-14 | IL
702 | Marcus | 2021-09-20 | GA
703 | Priya | 2023-01-18 | CO
Output:
- TOP_STATE_QUERY: [('IL', 2)]
- AVG_RATE_QUERY: [('2024-03-05', 2.3, 2.2), ('2024-03-08', 2.4, 2.4)]
- CUMULATIVE_QUERY: [('2024-03-05', 2, 2), ('2024-03-08', 2, 4)]
Explanation: All three pickup states (IL with 2 loads, CO and GA with 1 each) enter the top-5 shortlist, and IL leads with 2 completed jobs (11 and 14; cancelled job 13 is ignored). On 2024-03-05, the plain mean rate is (2.50 + 2.10) / 2 = 2.30, whereas the mile-weighted rate is (2.50 * 200 + 2.10 * 600) / 800 = 2.20. On 2024-03-08, zero-mile job 15 is excluded from AVG_RATE_QUERY (leaving 2.40), but counted in CUMULATIVE_QUERY so daily completions are 2 and 2 (running totals 2 and 4).
Example 2
Input:
- loads: OH (303, 304), PA (301, 302), IN (305), KY (306), MI (307), WI (308)
- jobs:
- job_id = 21 on load_id = 308 (WI), completed on 2024-04-01, 500 miles @ 3.00
- job_id = 22 on load_id = 308 (WI), completed on 2024-04-01, 300 miles @ 2.00
- job_id = 23 on load_id = 303 (OH), completed on 2024-04-02, 400 miles @ 2.50
- job_id = 24 on load_id = 301 (PA), completed on 2024-04-02, 100 miles @ 3.50
Output:
- TOP_STATE_QUERY: [('OH', 1)]
- AVG_RATE_QUERY: [('2024-04-01', 2.5, 2.625), ('2024-04-02', 3.0, 2.7)]
- CUMULATIVE_QUERY: [('2024-04-01', 2, 2), ('2024-04-02', 2, 4)]
Explanation: By distinct load count (DESC, then state ASC), the top-5 pickup states are OH (2), PA (2), IN (1), KY (1), and MI (1), so WI (1 load) misses the 5th-place tiebreaker even though WI has 2 completed jobs. Between OH (1) and PA (1), OH wins alphabetically.
Constraints
- Raw
loadsandjobstables may contain duplicate rows as well asNULLvalues inorigin_state,delivered_date,miles, orrate_per_mile. - Always count distinct
load_ids when ranking pickup states and distinctjob_ids when counting completed jobs. - Whole-number rates and miles must still produce exact floating-point division in SQLite (no integer division truncation).
- Empty tables must return zero rows (
[]) for all three queries; ifloadshas valid states but zero completed jobs exist,TOP_STATE_QUERYreturns the alphabetically first top-5 state withcompleted_jobs = 0.
Step-by-step walkthrough
Understand the schema and pin down the query contracts
We have three logistics tables, linked by foreign keys:
loads jobs drivers (unused) +---------+--------------+ +--------+---------+--------+-------+ +-----------+-------+ | load_id | origin_state | <---------- | job_id | load_id | status | miles | | driver_id | state | +---------+--------------+ load_id +--------+---------+--------+-------+ +-----------+-------+Notice
driversis not needed by any of the three questions — it is a classic distractor table in SQL screens. Before writing SQL, we state the exact rules where the prompt leaves choices open:- Which state column? A load's pickup state is
loads.origin_state, and ranking the top-5 pickup states countsCOUNT(DISTINCT load_id)per non-nullorigin_state. - Deterministic tie-breaking: ties in both the top-5 load ranking and the completed-job winner ranking are broken alphabetically (
state ASC). A top-5 state with zero completed jobs stays eligible with count0. - Task 2 averages: filter
status = 'completed',miles <> 0,rate_per_mile IS NOT NULL, anddelivered_date IS NOT NULL. Return both the plain per-job averageavg_rate_per_mileand the mile-weighted averageweighted_rate_per_mile = SUM(rate_per_mile * miles) / SUM(miles). - Task 3 cumulative count: count
DISTINCT job_idperdelivered_dateforstatus = 'completed'(including0-mile completed jobs — themiles <> 0filter applies only to Task 2), then accumulate across dates usingROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
- Which state column? A load's pickup state is
Task 1 (part 1): find the five busiest origin states
We break Task 1 into readable building blocks using Common Table Expressions (CTEs) — named temporary result sets introduced with
WITH name AS (...):state_loadsgroupsloadsbyorigin_state(excludingNULLstates so an unknown state never steals a top-5 slot) and countsCOUNT(DISTINCT load_id). UsingDISTINCT load_idprotects us if a load row was accidentally duplicated in raw ingestion.top_statessorts byload_count DESC, state ASCand keepsLIMIT 5. Includingstate ASCmakes 5th-place ties completely deterministic: ifAZ,MT, andORall tie at2loads for the 4th and 5th spots,AZandMTentertop_stateswhileORis cut.
-- Count distinct loads per non-null origin state so duplicate load rows are not double-counted. WITH state_loads AS ( SELECT origin_state AS state, COUNT(DISTINCT load_id) AS load_count FROM loads WHERE origin_state IS NOT NULL GROUP BY origin_state ), -- Keep the 5 busiest origin states, breaking load-count ties alphabetically. top_states AS ( SELECT state FROM state_loads ORDER BY load_count DESC, state ASC LIMIT 5 )Task 1 (part 2): count distinct completed jobs with LEFT JOIN
Next, we join
top_statestoloadsandjobsto count completed jobs per state. Two SQL details are critical here:- Put
j.status = 'completed'insideLEFT JOIN ... ON, NOT inWHERE: supposeINis intop_states, and its only job hasstatus = 'cancelled'(or no job at all). Compare what happens toIN:
Using LEFT JOIN ... ON j.load_id = l.load_id AND j.status = 'completed': t.state | l.load_id | j.job_id | j.status --------+-----------+----------+--------- IN | 305 | NULL | NULL --> COUNT(DISTINCT j.job_id) = 0 (kept!) If we instead wrote WHERE j.status = 'completed': The NULL row for IN fails WHERE NULL = 'completed' and vanishes completely!- Use
COUNT(DISTINCT j.job_id)instead ofCOUNT(*): ifload_id = 201appears3times inloads, joiningloadstojobsrepeats its completed job3times.COUNT(DISTINCT j.job_id)counts that job once, while still counting two genuinely differentjob_ids on the same load separately.
-- LEFT JOIN with j.status = 'completed' inside ON preserves top-5 states with 0 completed jobs. SELECT t.state, COUNT(DISTINCT j.job_id) AS completed_jobs FROM top_states AS t LEFT JOIN loads AS l ON l.origin_state = t.state LEFT JOIN jobs AS j ON j.load_id = l.load_id AND j.status = 'completed' GROUP BY t.state ORDER BY completed_jobs DESC, t.state ASC LIMIT 1On Example 1,
IL(2completed jobs),GA(1completed job), andCO(1completed job) all entertop_states, returning('IL', 2). On Example 2,OH(1) andPA(1) tie ahead ofIN,KY, andMI(0), soOHwins alphabetically with('OH', 1).- Put
Task 2: compute plain and mile-weighted daily rate averages
For Task 2, we filter
jobstostatus = 'completed',miles <> 0,rate_per_mile IS NOT NULL, anddelivered_date IS NOT NULL, thenGROUP BY delivered_date. Notice whyrate_per_mile IS NOT NULLmatters: SQL'sAVG(rate_per_mile)automatically skipsNULLrates, butSUM(miles)in our weighted denominator would still include that row's miles if we didn't exclude it inWHERE!Why compute both averages, and why write
* 1.0 / NULLIF(SUM(miles), 0)? Trace two completed jobs on2023-07-10:job_id | miles | rate_per_mile | job_pay = rate * miles -------+-------+---------------+----------------------- 10 | 100 | 2 | 200 11 | 300 | 3 | 900 -------+-------+---------------+----------------------- Totals: 400 mi 1100 dollars Plain mean: (2 + 3) / 2 = 2.50 (treats short and long hauls equally) Weighted mean: 1100 * 1.0 / 400 = 2.75 (true dollars earned per mile driven) Without '* 1.0': 1100 / 400 in SQLite = 2 (integer division truncates .75!)In SQLite, even a
DECIMAL(10, 2)column hasNUMERICaffinity, storing whole numbers like2.0as the integer2. Multiplying by1.0converts the numerator to floating-point before dividing, andNULLIF(SUM(miles), 0)turns a0denominator intoNULL(preventing division-by-zero errors in engines like PostgreSQL and Snowflake, and matching SQLite'sNULLbehavior).-- Exclude zero-mile, cancelled, and NULL rows before computing per-date unweighted and mile-weighted means. SELECT delivered_date, AVG(rate_per_mile) AS avg_rate_per_mile, -- Multiply by 1.0 so integer rates/miles do not truncate, and use NULLIF to guard zero denominators. SUM(rate_per_mile * miles) * 1.0 / NULLIF(SUM(miles), 0) AS weighted_rate_per_mile FROM jobs WHERE status = 'completed' AND miles <> 0 AND rate_per_mile IS NOT NULL AND delivered_date IS NOT NULL GROUP BY delivered_date ORDER BY delivered_dateTask 3: build a daily cumulative total with a window function
A window function (
SUM(...) OVER (...)) computes an aggregate across a sliding frame of rows without collapsing them. However,ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWcounts physical rows in the query stage where it runs! Compare running it directly on rawjobsrows versus running it after grouping by date:WRONG (window over raw jobs rows): RIGHT (aggregate to 'daily' CTE first): delivered_date | job_id | running_rows delivered_date | completed_jobs | cumulative ---------------+--------+------------- ---------------+----------------+----------- 2023-07-01 | 1 | 1 2023-07-01 | 2 | 2 2023-07-01 | 2 | 2 2023-07-03 | 3 | 5 2023-07-03 | 4 | 3So we first roll up
COUNT(DISTINCT job_id)perdelivered_datein adailyCTE (keeping0-mile completed jobs because Task 3 counts all completed jobs), and then runSUM(completed_jobs) OVER (ORDER BY delivered_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)over those one-row-per-date summaries.-- Roll up distinct completed jobs to one row per calendar date first (including 0-mile completed jobs). WITH daily AS ( SELECT delivered_date, COUNT(DISTINCT job_id) AS completed_jobs FROM jobs WHERE status = 'completed' AND delivered_date IS NOT NULL GROUP BY delivered_date ) -- Sum daily counts from the earliest date through the current date row. SELECT delivered_date, completed_jobs, SUM(completed_jobs) OVER ( ORDER BY delivered_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS cumulative_completed_jobs FROM daily ORDER BY delivered_dateTrace all three queries end-to-end on tricky edge cases
Let's verify Task 1's two-stage ranking on a tricky dataset where the states with the most completed jobs are not in the top 5 by load count:
State | Distinct loads | Rank in loads (top 5?) | Completed jobs | Eligible for winner? ------+----------------+------------------------------+----------------+--------------------- TX | 4 | #1 -> YES | 2 | yes CA | 3 | #2 (beats NV A->Z) -> YES | 3 | yes -> WINNER ('CA', 3) NV | 3 | #3 -> YES | 1 | yes AZ | 2 | #4 (beats MT, OR A->Z) -> YES| 0 | yes (kept at 0) MT | 2 | #5 (beats OR A->Z) -> YES | 1 | yes OR | 2 | #6 (cut by LIMIT 5!) -> NO | 4 | ignored WA | 1 | #7 -> NO | 5 | ignoredEven though
WAhas5completed jobs andORhas4, neither makes the top-5loadsshortlist, soTOP_STATE_QUERYrightly returns('CA', 3).Complete solution
# Three analytical SQLite queries over the jobs, loads, and drivers tables. # A job's state is the origin_state of its load; status is matched exactly ('completed'). # Task 1 — Return one row (state, completed_jobs): # Step A: rank non-null origin_states by distinct load_id count (ties broken A->Z) and keep 5. # Step B: count distinct completed job_ids among those 5 states, keeping 0-job states via LEFT JOIN. TOP_STATE_QUERY = """ -- Count distinct loads per non-null origin state so duplicate load rows are not double-counted. WITH state_loads AS ( SELECT origin_state AS state, COUNT(DISTINCT load_id) AS load_count FROM loads WHERE origin_state IS NOT NULL GROUP BY origin_state ), -- Keep the 5 busiest origin states, breaking load-count ties alphabetically. top_states AS ( SELECT state FROM state_loads ORDER BY load_count DESC, state ASC LIMIT 5 ) -- LEFT JOIN with j.status = 'completed' inside ON preserves top-5 states with 0 completed jobs. SELECT t.state, COUNT(DISTINCT j.job_id) AS completed_jobs FROM top_states AS t LEFT JOIN loads AS l ON l.origin_state = t.state LEFT JOIN jobs AS j ON j.load_id = l.load_id AND j.status = 'completed' GROUP BY t.state ORDER BY completed_jobs DESC, t.state ASC LIMIT 1 """ # Task 2 — Return one row per delivered_date ascending: # (delivered_date, avg_rate_per_mile, weighted_rate_per_mile) over completed non-zero-mile jobs. # Multiply by 1.0 to force floating-point division in SQLite, and guard SUM(miles) with NULLIF. AVG_RATE_QUERY = """ -- Exclude zero-mile, cancelled, and NULL rows before computing per-date unweighted and mile-weighted means. SELECT delivered_date, AVG(rate_per_mile) AS avg_rate_per_mile, -- Multiply by 1.0 so integer rates/miles do not truncate, and use NULLIF to guard zero denominators. SUM(rate_per_mile * miles) * 1.0 / NULLIF(SUM(miles), 0) AS weighted_rate_per_mile FROM jobs WHERE status = 'completed' AND miles <> 0 AND rate_per_mile IS NOT NULL AND delivered_date IS NOT NULL GROUP BY delivered_date ORDER BY delivered_date """ # Task 3 — Return one row per delivered_date ascending: # (delivered_date, completed_jobs, cumulative_completed_jobs). # Aggregate to one row per date FIRST so the ROWS window frame accumulates across dates, not raw rows. CUMULATIVE_QUERY = """ -- Roll up distinct completed jobs to one row per calendar date first (including 0-mile completed jobs). WITH daily AS ( SELECT delivered_date, COUNT(DISTINCT job_id) AS completed_jobs FROM jobs WHERE status = 'completed' AND delivered_date IS NOT NULL GROUP BY delivered_date ) -- Sum daily counts from the earliest date through the current date row. SELECT delivered_date, completed_jobs, SUM(completed_jobs) OVER ( ORDER BY delivered_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS cumulative_completed_jobs FROM daily ORDER BY delivered_date """✅ Submit now — all tests should pass.
Intuition & how it works
Think of analyzing this freight ledger like preparing summary tabs in a spreadsheet before computing final rankings or running totals. In Task 1, a Common Table Expression (CTE) (a named temporary subquery introduced with WITH that acts like a clean intermediate table) first builds the shortlist of the 5 busiest pickup states in loads, and a LEFT JOIN (a join that keeps every row from the left table and fills in NULLs when no matching row exists on the right) attaches completed jobs without dropping top-5 states that have 0 completed jobs. In Task 2, we filter out 0-mile and incomplete rows and compute both the plain per-job average and the weighted average (an average where each value is multiplied by its weight — here miles — before dividing by total weight). In Task 3, we collapse jobs to one summary row per date first, then run a window function (an SQL OVER (...) calculation that computes running or group-wide aggregates across neighboring rows without collapsing them into one row) with the window frame (the exact slice of rows included in each row's window calculation) ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
Naive SQL queries fail on four classic traps here. First, writing COUNT(*) after joining loads and jobs multiplies a job's count whenever its load_id appears in duplicate loads rows, while putting WHERE j.status = 'completed' after a LEFT JOIN discards the NULL-padded rows and erases 0-job states. Second, dividing SUM(rate_per_mile * miles) / SUM(miles) without * 1.0 performs integer division when whole-number rates like 2 and 3 are stored as integers, truncating 2.75 down to 2. Third, running ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW directly on raw jobs rows produces different running totals (1, 2, ...) for multiple jobs delivered on the same date instead of one clean cumulative number per day.
Walk through Example 1 (loads 201, 202 in IL, 203 in GA, 204 in CO; completed jobs 11 and 12 on 2024-03-05, cancelled job 13 on 2024-03-06, and completed jobs 14 (300 mi) and 15 (0 mi) on 2024-03-08):
- Task 1:
IL(2loads),CO(1load), andGA(1load) all entertop_states. Joining completed jobs givesIL -> 2,GA -> 1,CO -> 1, returning('IL', 2). - Task 2: cancelled job
13and zero-mile job15are excluded;2024-03-05outputs plain(2.50 + 2.10) / 2 = 2.3and mile-weighted(500 + 1260) / 800 = 2.2, followed by('2024-03-08', 2.4, 2.4). - Task 3: daily completed counts include zero-mile job
15, giving('2024-03-05', 2, 2)and('2024-03-08', 2, 4).
Complexity
Let L be the number of rows in loads, J be the number of rows in jobs, S be the number of distinct origin_states, and D be the number of distinct delivered_dates (D <= J).
- Task 1 —
O(L log L + J log J)without indexes: scanning and groupingloadsbyorigin_statewithCOUNT(DISTINCT load_id)sorts/indexes the(origin_state, load_id)pairs inO(L log L)time, sortingSstates takesO(S log S), and joining the 5 winning states toloadsandjobswithCOUNT(DISTINCT j.job_id)builds a temporary B-tree over the matched rows (O((L + J) log(L + J))in the worst case). - Tasks 2 and 3 —
O(J log J)without indexes: each query scansjobsonce to apply itsWHEREfilters, sorts/groups the qualifying rows bydelivered_date(O(J log J)), and in Task 3 walks theDordered daily summary rows in a singleO(D)pass to accumulate the runningSUM. - Space —
O(L + J)worst-case working memory: SQLite holds temporary B-trees forGROUP BYandCOUNT(DISTINCT)proportional to the grouped rows, while Task 3's window buffers only theDdaily rows. - Helpful composite indexes:
CREATE INDEX idx_loads_state_load ON loads(origin_state, load_id)lets Task 1 stream distinct(origin_state, load_id)pairs in sorted order without an extra sort;CREATE INDEX idx_jobs_load_status ON jobs(load_id, status, job_id)speeds up Task 1's join; andCREATE INDEX idx_jobs_status_date ON jobs(status, delivered_date)delivers completed jobs to Tasks 2 and 3 already ordered by date.
Edge cases
- Tie at the 5th-place load cutoff:
ORDER BY load_count DESC, state ASC LIMIT 5breaks ties alphabetically so exactly 5 states entertop_states. - Tie for most completed jobs:
ORDER BY completed_jobs DESC, t.state ASC LIMIT 1picks the alphabetically first tied state (OHahead ofPAin Example 2). - Top-5 states with zero completed jobs:
LEFT JOIN jobs AS j ON j.load_id = l.load_id AND j.status = 'completed'preserves all 5 states; if every job in the database is cancelled, the alphabetically first top-5 state wins with0. - Duplicate
loadsorjobsrows:COUNT(DISTINCT load_id),COUNT(DISTINCT j.job_id), andCOUNT(DISTINCT job_id)prevent duplicated rows from inflating any count, while still counting multiple distinctjob_ids on the sameload_id. NULLcolumns:WHERE origin_state IS NOT NULLkeeps unknown states out oftop_states;miles <> 0andrate_per_mile IS NOT NULLpreventNULLrates from inflatingSUM(miles)in Task 2's weighted denominator;delivered_date IS NOT NULLdrops undated jobs from Tasks 2 and 3.- Zero-mile completed jobs: excluded from Task 2 (
miles <> 0), but intentionally kept in Task 3 because a completed0-mile job (such as a local yard move or tonu/repositioned job) is still a completed job. - Integer-stored rates and zero mile sums:
* 1.0prevents SQLite integer division truncation, andNULLIF(NULLIF(a, b)returnsNULLwhena = bandaotherwise) safely guardsSUM(miles) = 0. - Empty tables: all three queries cleanly return
0rows ([]).
Common mistakes
- Filtering
WHERE j.status = 'completed'afterLEFT JOIN: aWHEREfilter runs after the outer join and discardsNULL-extended rows, turning yourLEFT JOINinto anINNER JOINand hiding states with0completed jobs. - Writing
COUNT(*)instead ofCOUNT(DISTINCT j.job_id):COUNT(*)counts1even for aNULL-paddedLEFT JOINrow (turning0completed jobs into1!) and double-counts jobs wheneverloadshas repeatedload_idrows. - Ranking states by completed jobs first instead of by
loadsfrequency first: the prompt asks for the completed-job leader among the 5 most frequent states inloads, which requires a two-step filter (top_statesCTE first, thenjobsjoin). - Applying
SUM(...) OVER (ORDER BY delivered_date ROWS ...)to ungroupedjobsrows: multiple jobs on2023-07-01then emit separate rows with partial running sums instead of one daily cumulative row. - Forgetting
* 1.0inSUM(rate_per_mile * miles) / SUM(miles): SQLite and PostgreSQL truncateinteger / integer(1100 / 400 -> 2instead of2.75). - Copying
AND miles <> 0into Task 3: Task 3 asks for the cumulative count of completed jobs, not just non-zero-mile jobs.
Alternative approaches
- Keeping all tied states with
RANK()orDENSE_RANK(): if business rules say every state tied for 5th place inloads(or tied for 1st incompleted_jobs) should be included rather than broken alphabetically, computeRANK() OVER (ORDER BY load_count DESC) AS rnkand filterWHERE rnk <= 5. - Standard SQL dialect equivalents: PostgreSQL, DuckDB, and Snowflake run all three queries unchanged (and also accept
FETCH FIRST 5 ROWS ONLYin place ofLIMIT 5); BigQuery usesSAFE_DIVIDE(a, b)as a shorthand fora * 1.0 / NULLIF(b, 0). - Equivalent
pandaspipeline: computetop5 = loads.dropna(subset=["origin_state"]).groupby("origin_state")["load_id"].nunique()..., left-merge completedjobsfor.nunique(), and usedaily["completed_jobs"].cumsum()for Task 3.
Follow-up questions
- How would you modify Task 1 if a load counted toward both its pickup state and its drop-off state? Unpivot both endpoints into a single
load_statesCTE usingUNION(SELECT load_id, origin_state AS state FROM loads UNION SELECT load_id, destination_state FROM loads), then rank and join throughload_states. BecauseUNIONdeduplicates identical(load_id, state)pairs automatically, an intra-stateIL -> ILload is counted once forIL, while an interstateIL -> OHload counts once forILand once forOH. - How can you include zero-delivery calendar days in the cumulative daily job table? Build a date spine (a continuous table of one row per calendar day between the minimum and maximum dates, generated via a recursive CTE
WITH RECURSIVE days(d) AS (...)that repeatedly adds+1 day),LEFT JOINthedailyCTE ontodays, wrapCOALESCE(daily.completed_jobs, 0), and run the sameSUM(...) OVER (ORDER BY days.d ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)window so quiet days appear withcompleted_jobs = 0and a flat running total. - For marketplace reporting, when is the mile-weighted daily rate preferable to the unweighted job average? They answer different operational questions: if one
50-mile local drayage job pays4.00/mi(200total) and one950-mile long-haul job pays2.00/mi(1,900total), the plain average is3.00/miwhile the mile-weighted average is2,100 / 1,000 = 2.10/mi. Use the mile-weighted rate for fleet unit economics, total revenue per mile, and margin forecasting; use the plain mean (or better, median grouped by haul-length bucket) to show drivers what a typical individual load pays.
Follow-up questions
- How would you modify Task 1 if a load counted toward both its pickup state and its drop-off state?
- How can you include zero-delivery calendar days in the cumulative daily job table?
- For marketplace reporting, when is the mile-weighted daily rate preferable to the unweighted job average?
Similar questions
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months
- Build Rolling User Features for Experiment Regression
- Week-over-Week Net Order Revenue Change