08 · SQL II: CTEs, window functions and time-series queries
Run it in Colab View the .ipynb
You are reading this notebook. To run it, open it in Colab with the button above - no install, no GPU needed for most of them - or clone the repository and open it in Jupyter.
- 1. Purpose
- 2. Conceptual explanation
- 2.1 Intuition: a window function adds a column without collapsing rows
- 2.2 Logical evaluation order
- 2.3 Frames, and the default that bites
- 2.4 Offsets:
LAG,LEADand intervals from events - 2.5 Gaps and islands: from samples to events
- 2.6 As-of joins and point-in-time correctness
- 2.7 The same operations in pandas
- 2.8 Industry example
- 2.9 Limits and misconceptions
- 3. Worked example: scan events on two packaging lines
- 4. Guided lab: six queries on cold-chain data
- Task 1 —
q1_latest_status.sql: one row per device (5 min) - Task 2 —
q2_time_in_state.sql: events to intervals (8 min) - Task 3 —
q3_running_alerts.sql: a running count that survives ties (6 min) - Task 4 —
q4_rolling_features.sql: a time window on an irregular grid (8 min) - Task 5 —
q5_alert_episodes.sql: gaps and islands (8 min) - Task 6 —
q6_asof_calibration.sql: as-of join (8 min) - Task 7 —
pandas_equiv.py: three functions (15 min) - Debugging guidance
- Task 1 —
- 5. Independent challenge: a point-in-time-correct feature table
- 6. Progressive hints
Week 2 · day 2 · 2 h essential path + up to 1 h optional · lab files: labs/w2d2_sql_windows_timeseries/
Objective. Use window functions for ranking, running statistics, gaps-and-islands and as-of joins on event and sensor tables; reproduce each result in pandas.
# --- Setup: works on your laptop AND in Google Colab ----------------------------
# In Colab this clones the course repository and installs the requirements (about a
# minute, first run only). On your own machine it just finds the repository. Every
# command in this notebook runs from the repository root. Safe to re-run.
import os
import subprocess
import sys
from pathlib import Path
if "google.colab" in sys.modules:
if not Path("/content/mlengineering").exists():
subprocess.run(["git", "clone", "--depth", "1",
"https://github.com/berdakh/mlengineering.git",
"/content/mlengineering"], check=True)
os.chdir("/content/mlengineering")
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"-r", "requirements.txt"], check=True)
REPO_ROOT = next(p for p in [Path.cwd(), *Path.cwd().parents]
if (p / "src" / "mlcourse").is_dir())
os.chdir(REPO_ROOT)
sys.path.insert(0, str(REPO_ROOT / "src"))
print("repo root:", REPO_ROOT)
Unit id: w2d2 · Week 2, day 2 · Content status: Execution verified (see Verification record)
Handbook: H3.2 Window functions and time-series SQL
Data: data/coldchain.db — SYNTHETIC, built to contain specific traps. Results in this lesson show that queries are correct; they say nothing about real equipment.
1. Purpose
Primary objective. Write window-function queries that are correct on tied, duplicated and irregularly sampled data — ranking, running statistics, run-length segmentation (gaps and islands) and as-of joins — and reproduce each result in pandas.
What you will learn
- Where window functions sit in SQL’s logical evaluation order, and why that forces CTEs.
- The three parts of a window (
PARTITION BY,ORDER BY, frame) and the default-frame trap. - Gaps and islands: turning a per-sample flag into events, inside the database.
- As-of joins and point-in-time correctness: the SQL form of “no future information”.
- The pandas idiom for each pattern, and where the two disagree at boundaries.
Why an applied ML engineer needs it. Features and labels are usually born in SQL, before any Python runs. The three failures this lesson targets all produce queries that execute, return the right number of rows and are wrong: a “latest row” that is not unique, a rolling window that silently counts rows instead of time, and a join that reads a value that did not exist yet at prediction time. The last one is temporal leakage, and it is far easier to commit in a join than in a training loop. Window functions are also the most common SQL interview topic above the join-and-group level.
Prerequisites. W2D1: stating the grain of a result, join
fan-out, NULL semantics. Python >= 3.11 whose sqlite3 module is linked against SQLite >= 3.28
(python -c "import sqlite3; print(sqlite3.sqlite_version)"; the checks tell you if it is too old).
No sqlite3 command-line tool is needed.
Time budget — essential path 2 h
| Activity | Time |
|---|---|
| Read section 2 (2.2, 2.3 and 2.6 carefully; skim what you know) | 25 min |
| Worked example: run it, predict each table before reading it | 15 min |
| Guided lab: six queries (40 min), three pandas functions (15 min) | 55 min |
| Independent challenge: specification, first working version | 15 min |
| Assessment questions (written) | 10 min |
Optional extension — up to 1 h: finish the challenge until its checks pass (30 min), interview rep (15 min), handbook H3.2.6 on engine differences (15 min).
2. Conceptual explanation
2.1 Intuition: a window function adds a column without collapsing rows
GROUP BY answers “one number per group” and destroys the rows. A window function answers “for
each row, a number computed from related rows” and keeps every row. Time-series work does
this constantly: a z-score against a unit’s own baseline, a moving RMS over the preceding second, the
sample index within a trial. In pandas these are groupby(...).transform(...), rolling(...),
groupby(...).cumcount(). SQL spells them all the same way:
function(args) OVER (PARTITION BY <who are my relatives> ORDER BY <in what sequence> <frame: which of them>)
| Part | Meaning | Signal-processing analogue |
|---|---|---|
PARTITION BY |
rows are only compared within the same partition | per subject / per channel / per trial |
ORDER BY |
the sequence inside a partition | the time axis |
| frame | which rows around the current one feed the function | the analysis window |
2.2 Logical evaluation order
A SELECT is evaluated, logically, in this order:
FROM / JOIN -> WHERE -> GROUP BY -> HAVING -> window functions -> SELECT list / DISTINCT -> ORDER BY -> LIMIT
Three consequences you will meet today:
- A window function cannot appear in
WHERE,GROUP BYorHAVING, because those run earlier. “Keep the row withrn = 1” therefore needs two levels: computernin a CTE or subquery, filter outside. SQLite’s message when you forget ismisuse of aliased window function rn. WHEREchanges what a window sees. A filter removes rows before the window is computed, soLAGreturns the previous surviving row. Filtering toalert = 1and then asking for the previous reading gives the previous alerting reading, which is rarely what you meant.- Windows run after aggregation, so
RANK() OVER (ORDER BY SUM(x) DESC)in a grouped query is legal and ranks the groups.
A CTE (WITH name AS (...)) is the tool for staging these levels. Treat each CTE as one step
with a stated grain, exactly as you would name intermediate DataFrames.
The same order as a diagram, with the place where each kind of filter can live:
2.3 Frames, and the default that bites
The frame is the subset of the partition used for the current row. Two units matter here:
ROWS BETWEEN 6 PRECEDING AND CURRENT ROWcounts physical rows.RANGE BETWEEN 1800 PRECEDING AND CURRENT ROWmeasures theORDER BYvalue: all rows whose key lies in[current − 1800, current]. It needs exactly one ordering key, numeric to be meaningful (hencets_epoch, not the textts).
With irregular sampling these are different windows. “Seven rows” is thirty minutes only if no sample was lost. On the lab data the two definitions give a different mean for 2,929 of 4,707 rows.
Peers. Rows with equal ORDER BY values are peers. Under RANGE, CURRENT ROW means “the
current row and all its peers”. Under ROWS it means the physical row.
The default frame. If you write ORDER BY inside OVER and no frame, the frame is
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
so a running total includes the current row’s peers. Two rows that tie get the same total, each
containing the other. With no ORDER BY at all, the frame is the whole partition.
For a cumulative sum \(S_i = \sum_{j \le i} x_j\) to be well defined, the index \(i\) must be a total order. So the rule is: make the ordering total (add a tie-breaker such as an id) and write the frame explicitly when you mean rows.
The ranking functions express the three possible attitudes to ties:
| Function | Ties | Values for scores 70, 55, 55, 40 |
|---|---|---|
ROW_NUMBER() |
broken arbitrarily unless the ordering is total | 1, 2, 3, 4 |
RANK() |
share a rank, then skip | 1, 2, 2, 4 |
DENSE_RANK() |
share a rank, no skip | 1, 2, 2, 3 |
“Top 1 per group” with RANK() = 1 (or WHERE ts = (SELECT MAX(ts) ...)) returns several rows
when the top is tied. If the result is then joined on the group key, every downstream row is
duplicated. Use ROW_NUMBER() with a deterministic tie-breaker when the contract is “exactly one”.
ROW_NUMBER() with a non-total ordering is worse than RANK(): it returns one row, but which one
may change between runs or engines.
One partition with a tied timestamp, three frames for the current row (marked >). Brackets show the
rows inside the frame; the right column is SUM(x) over it.
ts_epoch x ROWS 2 PRECEDING RANGE 600 PRECEDING default (ORDER BY, no frame)
AND CURRENT ROW AND CURRENT ROW = RANGE UNBOUNDED PRECEDING .. CURRENT ROW
1000 1 [
1300 2 [ [
2100 4 [ [ [
> 2400 8 [ = 2 + 4 + 8 = 14 [ [
2400 16 [ = 4 + 8 + 16 = 28 [ = 1 + 2 + 4 + 8 + 16 = 31
2900 32
ROWS counts physical rows: the peer at ts 2400 (x = 16) is outside.
RANGE measures the ORDER BY value: every row with ts in [1800, 2400] is inside, peers included.
The default frame is a RANGE frame, so a "running total" of the first 2400 row already contains the second.
2.4 Offsets: LAG, LEAD and intervals from events
LAG(x) and LEAD(x) read the previous and next row of the partition; they ignore the frame.
Two standard uses:
- Differences and gaps:
ts_epoch - LAG(ts_epoch) OVER (PARTITION BY device_id ORDER BY ts_epoch). - Events to intervals: a status log stores changes. The state that begins at one event ends at
the next one, so
LEAD(ts_epoch)gives the interval end. The last event has no successor; you must decide where it ends (a report horizon) and say so. Summing durations by state gives time-in-state. A cheap invariant: per device the durations must add up to the observed span.
2.5 Gaps and islands: from samples to events
In NumPy this is a familiar pattern: np.diff on a thresholded detector output, pair up
rising and falling edges, get events with onset and offset. The SQL form has the same two steps.
- Mark starts. A row starts an island if it is flagged and the previous row of the same
partition is not:
alert = 1 AND COALESCE(LAG(alert) OVER (...), 0) = 0. - Number islands. A running sum of the start marks is constant within an island and increases by one at each new start. Group by it.
alert 0 0 1 1 1 0 1 0 0 1 1
start 0 0 1 0 0 0 1 0 0 1 0
cumsum 0 0 1 1 1 1 2 2 2 3 3 <- on flagged rows this is the island number
An equivalent trick subtracts two row numbers (ROW_NUMBER() over all rows minus ROW_NUMBER()
over flagged rows is constant within a run). The start-mark version generalises better: change the
start condition to “gap since previous row > 30 minutes” and the same query sessionises by time
gap; change it to “status differs from previous” and it collapses repeated states.
Where the analogy with signal-based event detection breaks: detectors on a uniform sample grid (in physiology or audio, say) usually merge events closer than a refractory gap and discard events shorter than a minimum duration. Here “consecutive” means adjacent rows, and a lost sample between two flagged rows does not split the run. Whether that is right is a definition you owe the reader; state it (the lab does).
The classic error is forgetting the partition in step 1. LAG then looks at the previous row of
another device, which is the same bug as running event extraction across concatenated channels.
The reference query for Task 5 on one device and one day of the lab database:
Twenty-one flagged samples become five episodes. Two of them are a single sample wide: whether those
deserve to be events is the minimum-duration decision the text above says you owe the reader.
SYNTHETIC data; regenerate with python labs/w2d2_sql_windows_timeseries/figures/make_figures.py.
2.6 As-of joins and point-in-time correctness
Some tables describe what was true from when: a calibration, a price list, a customer’s plan, a model version. For a fact at time \(t\) you need the dimension row in force at \(t\):
\[\text{match}(t) = \arg\max_{k} \{\, v_k : v_k \le t \,\}\]where \(v_k\) are the valid_from times of that entity’s rows. This is an as-of join. Standard SQL
has no single keyword for it; the portable pattern is: join on the entity key and
valid_from <= t, then keep the latest match per fact row with ROW_NUMBER(). Use a LEFT JOIN
so that facts older than the first dimension row survive with NULLs rather than vanishing.
The same construction defines a point-in-time-correct feature. For a label observed at prediction time \(t_\ell\), a feature may be any function of rows with timestamp \(\le t_\ell\) and of nothing else:
\[f_\ell = g\big(\{\, r : \text{entity}(r) = \text{entity}(\ell),\ t_r \le t_\ell \,\}\big)\]This gives a property you can test without knowing the right answer: edit every row after \(t_\ell\) arbitrarily; \(f_\ell\) must not change. The challenge checks use exactly this.
Three ways a join reads the future, all common:
| Mistake | What it looks like |
|---|---|
| Join to the current dimension row | JOIN calibration USING (device_id) on a “latest” view |
| Symmetric window | ABS(r.ts - l.label_ts) <= 3600, a centred window carried over from offline analysis |
| Nearest instead of previous | ORDER BY ABS(r.ts - l.label_ts), or merge_asof(direction="nearest") |
There is one more that no query can detect: a row whose timestamp is in the past but which was
written later (a backfilled or corrected value, such as the re-sent readings in today’s data).
Point-in-time correctness is about when information became available, which needs an ingestion
time. Today’s data has only reading_id as a proxy for arrival order; H3.2.5 discusses this.
On the lab database, device D01 changes calibration four times in three days. Each reading is corrected with the offset, and compared with the threshold, that were in force when it was measured:
Joining every reading to the latest calibration row instead would re-score three days of history with an offset and threshold that did not exist yet. SYNTHETIC data, same script.
2.7 The same operations in pandas
| SQL | pandas | Boundary to watch |
|---|---|---|
ROW_NUMBER() OVER (PARTITION BY g ORDER BY k) |
df.sort_values(k).groupby(g).cumcount() + 1 |
sort first; ties need a total order in both |
RANK() / DENSE_RANK() |
groupby(g)[k].rank(method="min" / "dense") |
default method="average" matches neither |
LAG(x) / LEAD(x) |
groupby(g)[x].shift(1) / shift(-1) |
a bare df.x.shift() crosses groups |
running sum, ROWS frame |
groupby(g)[x].cumsum() |
row order is whatever the frame currently has |
RANGE BETWEEN 1800 PRECEDING AND CURRENT ROW |
rolling("1800s", closed="both") on a datetime index |
pandas’ default is closed="right": (t−30 min, t] |
aggregate OVER (PARTITION BY g) |
groupby(g)[x].transform("mean") |
— |
| as-of join | pd.merge_asof(left, right, on=..., by=..., direction="backward") |
both frames sorted by the on key; allow_exact_matches=True means <= |
| top-1 per group | sort_values(...).groupby(g).head(1) or drop_duplicates(g, keep="last") |
— |
Pushing work into SQL is not a matter of taste: the database filters and aggregates next to the data, and the feature definition lives where the serving path can reuse it. Pandas is the better place to prototype and to test. Doing both and asserting equality, as today, is a cheap way to find the boundary cases neither version handles on its own.
2.8 Industry example
A logistics company bills cold-chain customers for temperature compliance. The compliance report is three of today’s queries: the current status of each unit (latest row per device), hours spent in each state last month (events to intervals), and excursion episodes with duration and peak (gaps and islands on calibrated readings joined as of each reading’s time). A re-calibration in the middle of the month must not rewrite last week’s excursions; that is the as-of join. When the same company later trains a failure-prediction model, the feature table is the challenge query, and the first model review asks precisely whether any feature could see past the inspection time.
2.9 Limits and misconceptions
- “The query ran and the row count is right, so it is right.” Every mutant kept for this lesson satisfies both. Check the grain, check ties, check a boundary case.
- “
ROW_NUMBERmakes it deterministic.” Only if the ordering is total. - “
ORDER BYin the window sorts the output.” It orders rows for the function only; the result order is undefined without a finalORDER BY. - “A window function is slow / always fast.” It needs a sort per distinct window; an index on
(partition key, order key)can supply it. The range-join form of an as-of join is quadratic per entity in the worst case. Fine for today’s data; see H3.2.6 for what engines offer. - “SQLite behaves like the warehouse.” The window semantics used today are standard. Time arithmetic, types and named as-of syntax differ by engine.
3. Worked example: scan events on two packaging lines
File: example/window_tour.py. Fourteen hand-typed scan events
(SYNTHETIC, small enough to follow by eye) in an in-memory SQLite table:
| Column | Type | Meaning |
|---|---|---|
event_id |
int | log order |
line |
text | packaging line, A or B |
ts |
text | scan time |
operator |
text | who scanned |
units |
int | units in the scanned batch |
Planted on purpose: events 2 and 3 share a timestamp and a unit count; event 9 is an exact re-send of event 8; there are gaps of more than 30 minutes.
!python labs/w2d2_sql_windows_timeseries/example/window_tour.py
The script runs five patterns and asserts that each equals its pandas equivalent. Output of the run on 2026-11-21 (SQLite 3.53.1, pandas 3.0.5), abridged to the three tables worth studying:
--- 1. ranking functions on line A, ORDER BY units DESC ---
event_id line units row_number rank dense_rank
5 A 70 1 1 1
2 A 55 2 2 2
3 A 55 3 2 2
1 A 40 4 4 3
4 A 30 5 5 4
6 A 20 6 6 5
--- 3. running total on line A: default frame versus explicit ROWS ---
event_id ts units default_frame rows_frame
1 2026-05-04 08:00:00 40 40 40
2 2026-05-04 08:10:00 55 150 95
3 2026-05-04 08:10:00 55 150 150
4 2026-05-04 08:25:00 30 180 180
5 2026-05-04 09:40:00 70 250 250
6 2026-05-04 09:55:00 20 270 270
--- 4. de-duplicated, sessionised by a 30-minute gap ---
line session_no start_ts end_ts n_scans units
A 1 2026-05-04 08:00:00 2026-05-04 08:25:00 4 180
A 2 2026-05-04 09:40:00 2026-05-04 09:55:00 2 90
B 1 2026-05-04 08:05:00 2026-05-04 08:45:00 3 160
B 2 2026-05-04 10:30:00 2026-05-04 10:40:00 2 50
B 3 2026-05-04 11:30:00 2026-05-04 11:35:00 2 105
...
All five SQL results equal their pandas equivalents.
Reading the output
- Table 1. The three functions agree until the tie at 55 units. Which of events 2 and 3 gets
row_number2 is not determined byORDER BY units DESC; it happened to be event 2. - Table 3. Event 2’s
default_frametotal is 150, not 95: it already contains event 3, its peer. Nothing fails, and the last row of the partition is correct in both columns, which is why this bug survives a glance at totals. - Table 4. Line B, session 1 has three scans, not four, because the exact duplicate was removed first. De-duplicating after sessionising would have given 250 units instead of 160.
Code decisions worth noticing
- The top-1 query (pattern 2 in the script) is shown twice, with
RANKand withROW_NUMBERplusevent_idas tie-breaker. Line B has two rows in the first version. - Sessionisation is three CTEs —
dedup,gaps,numbered— each with one job. The start condition isgap_min IS NULL OR gap_min > 30: the first row of a partition has no predecessor and must start a session explicitly, becauseNULL > 30is not true. - The pandas version of the ranking uses
rank(method="min")andrank(method="dense"). The default,method="average", would give 2.5 for the tied rows and matches no SQL function. - Every comparison sorts both results by a key first. SQL results have no inherent order.
Reproduce: the script has no inputs and no randomness; the output above should match exactly apart from the version line.
4. Guided lab: six queries on cold-chain data
You produce: six SQL files in lab/queries/ and three functions in
lab/pandas_equiv.py. Each starter file contains the full specification
(source, grain, columns, rules) and a placeholder statement.
Read data/README.md first (3 minutes): it lists the tables and the properties
built into the data. Then explore:
!python labs/w2d2_sql_windows_timeseries/lab/run_query.py --sql "SELECT * FROM device_status_events LIMIT 8"
!python labs/w2d2_sql_windows_timeseries/lab/run_query.py q1
!python labs/w2d2_sql_windows_timeseries/lab/run_query.py q5 --where "device_id = 'D03'" --rows 30
!python wb.py check w2d2
!python -m pytest labs/w2d2_sql_windows_timeseries/checks -q -k q1
The checks run every query on the shipped database and on a second database generated from a different seed, and compare with results computed independently in plain Python. Column names must match the specification; column order and row order do not matter.
Before each query, write its grain in a comment at the top (you did this in W2D1). It is the fastest way to notice a wrong result.
Task 1 — q1_latest_status.sql: one row per device (5 min)
Latest status per device, with log order deciding between equal timestamps.
Checkpoint: exactly 6 rows. Then run this and explain the difference to yourself:
!python labs/w2d2_sql_windows_timeseries/lab/run_query.py --sql "SELECT device_id, COUNT(*) FROM device_status_events e WHERE ts_epoch = (SELECT MAX(ts_epoch) FROM device_status_events WHERE device_id = e.device_id) GROUP BY 1"
Task 2 — q2_time_in_state.sql: events to intervals (8 min)
Seconds per device and status. LEAD has a three-argument form, LEAD(expr, offset, default),
which is the neat way to close the last interval.
Checkpoint: 24 rows (6 devices × 4 statuses in the shipped data). For each device the seconds must sum to the time from its first event to the report end; all six devices start at 2026-03-01 00:00:00, so each total is 259,200.
Task 3 — q3_running_alerts.sql: a running count that survives ties (6 min)
This one runs on the raw table, where a measurement can appear twice with the same timestamp.
Checkpoint: 4,811 rows. Write the obvious version first
(SUM(alert) OVER (PARTITION BY device_id ORDER BY ts_epoch)), then find a row where it is wrong:
python labs/w2d2_sql_windows_timeseries/lab/run_query.py q3 --where "reading_id IN (SELECT MIN(reading_id) FROM sensor_readings GROUP BY device_id, ts_epoch HAVING COUNT(*) > 1 AND MIN(alert) <> MAX(alert))" --rows 5
Compare the count on such a row with the count on the row just before it in (ts_epoch, reading_id) order.
Task 4 — q4_rolling_features.sql: a time window on an irregular grid (8 min)
From here on use the view readings_dedup. Look at its definition first:
!python labs/w2d2_sql_windows_timeseries/lab/run_query.py --sql "SELECT sql FROM sqlite_master WHERE name = 'readings_dedup'"
Two windows are needed (one for the 30-minute frame, one for LAG). A WINDOW clause after
FROM lets you name them once: WINDOW seq AS (...), w30 AS (...).
Checkpoint: 4,707 rows; n_30m ranges from 1 to 8; gap_s has median 302 and maximum 7,734; delta_prev and
gap_s are NULL on exactly 6 rows.
Task 5 — q5_alert_episodes.sql: gaps and islands (8 min)
Checkpoint: 113 episodes in the shipped data, the longest 15 samples. Sanity check you can
compute yourself: the sum of n_samples equals SELECT SUM(alert) FROM readings_dedup.
Task 6 — q6_asof_calibration.sql: as-of join (8 min)
Checkpoint: 4,707 rows — the same as readings_dedup; if you have fewer, a join dropped rows; if
more, you kept more than one calibration row per reading. 68 rows (all D06, before 06:00 on the
first day) have NULL in the three computed columns.
Task 7 — pandas_equiv.py: three functions (15 min)
Implement rolling_features, alert_episodes and asof_calibration. The checks compare each
with the specification and with your own SQL result.
Checkpoint: python wb.py check w2d2 passes all 26 checks, in about 2 seconds.
Debugging guidance
| Symptom | Likely cause |
|---|---|
misuse of aliased window function rn |
You filtered on a window result in the same SELECT. Move the window into a CTE (section 2.2). |
more than one row per ['device_id'] |
Ties: your ordering is not total, or you used RANK. |
| q2 totals do not sum to the span | The last interval is not closed, or LEAD is ordered by ts_epoch alone and a tied pair is taken in the wrong order. |
| q3 differs on “26 of 4811 rows” or similar small count | Default frame; peers are being added to each other. |
q4 temp_mean_30m differs on thousands of rows |
A ROWS frame where time was meant. |
| q4 differs on a handful of rows | Window boundary: is t − 1800 itself included? |
| q5 has several times too many episodes | LAG without PARTITION BY device_id. |
| q6 has NULLs in different rows than expected | Inner join dropped the uncalibrated period, or a later calibration was applied to earlier readings. |
pandas ValueError: left keys must be sorted |
merge_asof needs both frames sorted by the on key (globally, not within by). |
| pandas rolling result is misaligned | After groupby(...).rolling(...) the result has a (group, time) index; align by position only if your frame is sorted the same way. |
pandas ValueError: index values must be monotonic |
Sort by time within each group before a time-based rolling. |
Do not print whole tables to find a wrong row. Filter the result with --where, or select the
rows around one timestamp for one device.
# Run the automated checks on your guided lab.
# A fresh starter is expected to FAIL; passing means guided practice, not mastery.
from mlcourse.checks import check
check("w2d2")
5. Independent challenge: a point-in-time-correct feature table
Specification and acceptance criteria: challenge/README.md. You write one
query, challenge/features.sql, producing five features for each of the
38 rows of maintenance_labels, using only information available at the label time.
!python wb.py check w2d2 --challenge
No solution is linked from here. The check that matters rewrites everything after each label’s timestamp and requires that label’s features to stay exactly the same.
The challenge brief
Type: independent transfer task. No walkthrough, no starter beyond a placeholder.
Time: 15 minutes inside the essential path to get a first version; about 30 more to pass the checks.
Data: data/coldchain.db, SYNTHETIC (see ../data/README.md).
Scenario
The operations team inspects refrigeration units. Each row of maintenance_labels is one
inspection: label_ts is the moment a prediction would have been made, and failed says whether
the unit failed within the following hour. You are asked for the feature table a first failure
model would be trained on. The model will run at inspection time, so a feature may use only what
was recorded at or before label_ts for that unit.
Task
Write one SQL statement in features.sql that returns exactly one row per
label with these columns:
| Column | Definition (all for the label’s own device) |
|---|---|
label_id |
from maintenance_labels |
failed |
from maintenance_labels, unchanged |
last_temperature |
temperature of the most recent reading with ts_epoch <= label_ts_epoch; NULL if there is none |
mean_temp_60m |
mean temperature of readings with label_ts_epoch - 3600 < ts_epoch <= label_ts_epoch; NULL if there are none |
n_alerts_24h |
number of readings with alert = 1 and label_ts_epoch - 86400 < ts_epoch <= label_ts_epoch; 0 if there are none |
seconds_since_fault |
label_ts_epoch minus the ts_epoch of the most recent fault status event at or before the label; NULL if there is none |
status_at_label |
the device status in force at label_ts (latest status event at or before it; log order breaks ties); NULL if there is none |
“Reading” means a row of the view readings_dedup. Status events come from device_status_events.
Acceptance criteria
python wb.py check w2d2 --challengepasses. The checks require that- the result matches the definitions above on the shipped database and on a re-seeded one;
- every label yields exactly one row, including a label whose device has no history at all;
- for every label, rewriting all readings and status events later than its
label_tsleaves that label’s five features unchanged.
- Each CTE in your query has a one-line comment stating its grain.
- In
progress/notes.md(python wb.py note w2d2 "..."), three or four sentences answering: which single condition in your query is responsible for point-in-time correctness of each feature, and how would you convince a reviewer who does not read SQL?
Then look at what you built (5 minutes, part of the task)
Compute, for each feature, how well it separates failed = 1 from failed = 0 (for example the
ROC AUC of the raw feature with scikit-learn). Write down what you see and what you conclude,
keeping in mind there are 38 labels. Then change one of your windows to look one hour past the
label and repeat. This comparison is discussed in the assessment answers; do it before reading them.
Out of scope
No model training, no pandas version (optional: reproduce the table with merge_asof and
rolling, and assert equality with your SQL result).
# Run the automated checks on your independent challenge.
# A fresh starter is expected to FAIL; passing means guided practice, not mastery.
from mlcourse.checks import check
check("w2d2", challenge=True)
6. Progressive hints
Open them in order, and only after a real attempt. They apply to the challenge; the lab has its own debugging table above.
The full reference solution is in solutions/labs/w2d2_sql_windows_timeseries/. Opening it
before your own version passes means the independent flag stays unset for this unit.
Open one hint at a time, only after a real attempt.