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:

  1. TOP_STATE_QUERY — Completed-job leader among top-5 pickup states:

    • Rank non-null loads.origin_state values by their number of distinct load_ids descending, breaking ties alphabetically (origin_state ASC), and keep at most 5 states.
    • Among that shortlist of up to 5 pickup states, count each state's distinct completed job_ids (jobs.status = 'completed'). A shortlisted state with zero completed jobs must remain eligible with count 0.
    • Output a single row (state, completed_jobs) for the shortlisted state with the highest completed_jobs count (breaking ties alphabetically by state ASC), or zero rows if loads has no non-null origin_state.
  2. AVG_RATE_QUERY — Daily unweighted and mile-weighted haul rates:

    • Filter jobs to rows where status = 'completed', miles is non-null and miles <> 0, rate_per_mile IS NOT NULL, and delivered_date IS NOT NULL.
    • Group by delivered_date and return (delivered_date, avg_rate_per_mile, weighted_rate_per_mile) ordered by delivered_date ascending, where:
      • avg_rate_per_mile is the plain arithmetic mean of rate_per_mile on that date, and
      • weighted_rate_per_mile is SUM(rate_per_mile * miles) / SUM(miles) computed with real floating-point division.
  3. CUMULATIVE_QUERY — Daily and running completed job counts:

    • Filter jobs to rows where status = 'completed' and delivered_date IS NOT NULL (completed jobs with miles = 0 are counted here).
    • Return one row per delivered_date in ascending order with columns (delivered_date, completed_jobs, cumulative_completed_jobs), where completed_jobs is the count of distinct job_ids completed on that date and cumulative_completed_jobs is the running sum across ordered date rows using a window function (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW).

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 loads and jobs tables may contain duplicate rows as well as NULL values in origin_state, delivered_date, miles, or rate_per_mile.
  • Always count distinct load_ids when ranking pickup states and distinct job_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; if loads has valid states but zero completed jobs exist, TOP_STATE_QUERY returns the alphabetically first top-5 state with completed_jobs = 0.

Step-by-step walkthrough

  1. 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 drivers is 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 counts COUNT(DISTINCT load_id) per non-null origin_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 count 0.
    • Task 2 averages: filter status = 'completed', miles <> 0, rate_per_mile IS NOT NULL, and delivered_date IS NOT NULL. Return both the plain per-job average avg_rate_per_mile and the mile-weighted average weighted_rate_per_mile = SUM(rate_per_mile * miles) / SUM(miles).
    • Task 3 cumulative count: count DISTINCT job_id per delivered_date for status = 'completed' (including 0-mile completed jobs — the miles <> 0 filter applies only to Task 2), then accumulate across dates using ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
  2. 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 (...):

    1. state_loads groups loads by origin_state (excluding NULL states so an unknown state never steals a top-5 slot) and counts COUNT(DISTINCT load_id). Using DISTINCT load_id protects us if a load row was accidentally duplicated in raw ingestion.
    2. top_states sorts by load_count DESC, state ASC and keeps LIMIT 5. Including state ASC makes 5th-place ties completely deterministic: if AZ, MT, and OR all tie at 2 loads for the 4th and 5th spots, AZ and MT enter top_states while OR is 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
    )
    
  3. Task 1 (part 2): count distinct completed jobs with LEFT JOIN

    Next, we join top_states to loads and jobs to count completed jobs per state. Two SQL details are critical here:

    1. Put j.status = 'completed' inside LEFT JOIN ... ON, NOT in WHERE: suppose IN is in top_states, and its only job has status = 'cancelled' (or no job at all). Compare what happens to IN:
      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!
    
    1. Use COUNT(DISTINCT j.job_id) instead of COUNT(*): if load_id = 201 appears 3 times in loads, joining loads to jobs repeats its completed job 3 times. COUNT(DISTINCT j.job_id) counts that job once, while still counting two genuinely different job_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 1
    

    On Example 1, IL (2 completed jobs), GA (1 completed job), and CO (1 completed job) all enter top_states, returning ('IL', 2). On Example 2, OH (1) and PA (1) tie ahead of IN, KY, and MI (0), so OH wins alphabetically with ('OH', 1).

  4. Task 2: compute plain and mile-weighted daily rate averages

    For Task 2, we filter jobs to status = 'completed', miles <> 0, rate_per_mile IS NOT NULL, and delivered_date IS NOT NULL, then GROUP BY delivered_date. Notice why rate_per_mile IS NOT NULL matters: SQL's AVG(rate_per_mile) automatically skips NULL rates, but SUM(miles) in our weighted denominator would still include that row's miles if we didn't exclude it in WHERE!

    Why compute both averages, and why write * 1.0 / NULLIF(SUM(miles), 0)? Trace two completed jobs on 2023-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 has NUMERIC affinity, storing whole numbers like 2.0 as the integer 2. Multiplying by 1.0 converts the numerator to floating-point before dividing, and NULLIF(SUM(miles), 0) turns a 0 denominator into NULL (preventing division-by-zero errors in engines like PostgreSQL and Snowflake, and matching SQLite's NULL behavior).

    -- 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
    
  5. Task 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 ROW counts physical rows in the query stage where it runs! Compare running it directly on raw jobs rows 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      | 3
    

    So we first roll up COUNT(DISTINCT job_id) per delivered_date in a daily CTE (keeping 0-mile completed jobs because Task 3 counts all completed jobs), and then run SUM(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_date
    
  6. Trace 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              | ignored
    

    Even though WA has 5 completed jobs and OR has 4, neither makes the top-5 loads shortlist, so TOP_STATE_QUERY rightly returns ('CA', 3).

  7. 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):

  1. Task 1: IL (2 loads), CO (1 load), and GA (1 load) all enter top_states. Joining completed jobs gives IL -> 2, GA -> 1, CO -> 1, returning ('IL', 2).
  2. Task 2: cancelled job 13 and zero-mile job 15 are excluded; 2024-03-05 outputs plain (2.50 + 2.10) / 2 = 2.3 and mile-weighted (500 + 1260) / 800 = 2.2, followed by ('2024-03-08', 2.4, 2.4).
  3. 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 grouping loads by origin_state with COUNT(DISTINCT load_id) sorts/indexes the (origin_state, load_id) pairs in O(L log L) time, sorting S states takes O(S log S), and joining the 5 winning states to loads and jobs with COUNT(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 scans jobs once to apply its WHERE filters, sorts/groups the qualifying rows by delivered_date (O(J log J)), and in Task 3 walks the D ordered daily summary rows in a single O(D) pass to accumulate the running SUM.
  • Space — O(L + J) worst-case working memory: SQLite holds temporary B-trees for GROUP BY and COUNT(DISTINCT) proportional to the grouped rows, while Task 3's window buffers only the D daily 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; and CREATE 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 5 breaks ties alphabetically so exactly 5 states enter top_states.
  • Tie for most completed jobs: ORDER BY completed_jobs DESC, t.state ASC LIMIT 1 picks the alphabetically first tied state (OH ahead of PA in 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 with 0.
  • Duplicate loads or jobs rows: COUNT(DISTINCT load_id), COUNT(DISTINCT j.job_id), and COUNT(DISTINCT job_id) prevent duplicated rows from inflating any count, while still counting multiple distinct job_ids on the same load_id.
  • NULL columns: WHERE origin_state IS NOT NULL keeps unknown states out of top_states; miles <> 0 and rate_per_mile IS NOT NULL prevent NULL rates from inflating SUM(miles) in Task 2's weighted denominator; delivered_date IS NOT NULL drops 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 completed 0-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.0 prevents SQLite integer division truncation, and NULLIF (NULLIF(a, b) returns NULL when a = b and a otherwise) safely guards SUM(miles) = 0.
  • Empty tables: all three queries cleanly return 0 rows ([]).

Common mistakes

  • Filtering WHERE j.status = 'completed' after LEFT JOIN: a WHERE filter runs after the outer join and discards NULL-extended rows, turning your LEFT JOIN into an INNER JOIN and hiding states with 0 completed jobs.
  • Writing COUNT(*) instead of COUNT(DISTINCT j.job_id): COUNT(*) counts 1 even for a NULL-padded LEFT JOIN row (turning 0 completed jobs into 1!) and double-counts jobs whenever loads has repeated load_id rows.
  • Ranking states by completed jobs first instead of by loads frequency first: the prompt asks for the completed-job leader among the 5 most frequent states in loads, which requires a two-step filter (top_states CTE first, then jobs join).
  • Applying SUM(...) OVER (ORDER BY delivered_date ROWS ...) to ungrouped jobs rows: multiple jobs on 2023-07-01 then emit separate rows with partial running sums instead of one daily cumulative row.
  • Forgetting * 1.0 in SUM(rate_per_mile * miles) / SUM(miles): SQLite and PostgreSQL truncate integer / integer (1100 / 400 -> 2 instead of 2.75).
  • Copying AND miles <> 0 into 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() or DENSE_RANK(): if business rules say every state tied for 5th place in loads (or tied for 1st in completed_jobs) should be included rather than broken alphabetically, compute RANK() OVER (ORDER BY load_count DESC) AS rnk and filter WHERE rnk <= 5.
  • Standard SQL dialect equivalents: PostgreSQL, DuckDB, and Snowflake run all three queries unchanged (and also accept FETCH FIRST 5 ROWS ONLY in place of LIMIT 5); BigQuery uses SAFE_DIVIDE(a, b) as a shorthand for a * 1.0 / NULLIF(b, 0).
  • Equivalent pandas pipeline: compute top5 = loads.dropna(subset=["origin_state"]).groupby("origin_state")["load_id"].nunique()..., left-merge completed jobs for .nunique(), and use daily["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_states CTE using UNION (SELECT load_id, origin_state AS state FROM loads UNION SELECT load_id, destination_state FROM loads), then rank and join through load_states. Because UNION deduplicates identical (load_id, state) pairs automatically, an intra-state IL -> IL load is counted once for IL, while an interstate IL -> OH load counts once for IL and once for OH.
  • 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 JOIN the daily CTE onto days, wrap COALESCE(daily.completed_jobs, 0), and run the same SUM(...) OVER (ORDER BY days.d ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) window so quiet days appear with completed_jobs = 0 and 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 pays 4.00/mi (200 total) and one 950-mile long-haul job pays 2.00/mi (1,900 total), the plain average is 3.00/mi while the mile-weighted average is 2,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

Similar questions

More CloudTrucks interview questions

All 1 CloudTrucks questions →