Databases & SQL Master Course — 090. Window Analytics Practice Lab
Lesson 090 Window Analytics Practice Lab
Prerequisites and objectives
Combine window totals, ranking, offsets, frames, and filter placement. You will build a regional daily report with cumulative net value, prior-observation change, and tie-aware ranking, then reconcile it independently. The lab deliberately includes a negative day, tied amounts, and a missing date.
Create the practice fixture
Use a fresh SQLite database. One row represents one region and recorded calendar day. Net amounts are integer cents in one fictional currency; a negative amount is permitted by this reporting model. South has no October second row. Absence is not automatically interpreted as a zero-activity day.
CREATE TABLE regional_days (region TEXT NOT NULL,day TEXT NOT NULL,net_cents INTEGER NOT NULL,PRIMARY KEY(region,day));
INSERT INTO regional_days VALUES ('North','2026-10-01',100),('North','2026-10-02',200),('North','2026-10-03',-50),('North','2026-10-04',200),('South','2026-10-01',80),('South','2026-10-03',120);
Write the report contract
The cumulative measure includes every recorded day from the fixture’s beginning through the current day, separately for each region. The prior comparison uses the previous recorded observation, not necessarily yesterday. Ranking uses descending net amount within the region and preserves equal-amount ties.
These are three different window specifications because they answer three different questions. Sharing one named window blindly would risk giving ranking a chronological order or giving cumulative totals a score order. Reuse specifications only when their semantics genuinely match.
WITH context AS (SELECT region,day,net_cents,
SUM(net_cents) OVER (PARTITION BY region ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cumulative_cents,
LAG(net_cents) OVER (PARTITION BY region ORDER BY day) AS previous_net,
LAG(day) OVER (PARTITION BY region ORDER BY day) AS previous_day,
RANK() OVER (PARTITION BY region ORDER BY net_cents DESC) AS score_rank
FROM regional_days) SELECT region,day,net_cents,cumulative_cents FROM context ORDER BY region,day;
| Region | Day | Daily net | Cumulative net |
|---|---|---|---|
| North | 2026-10-01 | 100 | 100 |
| North | 2026-10-02 | 200 | 300 |
| North | 2026-10-03 | -50 | 250 |
| North | 2026-10-04 | 200 | 450 |
| South | 2026-10-01 | 80 | 80 |
| South | 2026-10-03 | 120 | 200 |
North rises to 300, falls to 250 on its negative day, and ends at 450. South ends at 200. A cumulative net measure need not increase monotonically when negative contributions are valid. Treating the dip as a query error would confuse a business fact with a computational failure.

Keep calculation scope separate from display scope
A report showing only positive days should still include the negative day in later cumulative totals if the contract is full-history net value. Calculate context first, then filter the presentation. Removing the negative row before summing would inflate North’s final value to 500.
A top-day report has a different selection criterion. Ranking by amount can identify strong days while cumulative totals remain chronological. A high rank does not imply that a day occurred late or caused the final balance. Keep labels and columns explicit so readers do not blend unrelated meanings.
Expose irregular observation spacing
South’s October third comparison points to October first. The amount difference is forty cents across two calendar days, not a one-day change. Include the previous date or gap length if a reader might otherwise interpret the difference as daily growth.
If the requirement calls for true day-over-day change, introduce a complete calendar and a documented missing-day policy before calculating LAG. Zero-filling absent dates is a domain decision. The current lab intentionally reports adjacent recorded observations instead.
Validate the whole report
Check output grain first: there should still be six regional-day rows. Then verify tie behavior, first-row NULL offsets, the negative-day cumulative dip, and South’s two-day gap. Finally, reconcile each region’s last cumulative value with a direct grouped sum from the source.
Do not sum every cumulative value to obtain a regional total; that repeatedly counts earlier days. The final cumulative value under chronological ordering is meaningful here, while MAX of the cumulative series is not a universal substitute when later negative values can reduce the ending balance.
Four worked exercises
Exercise 1
List days within the first two competition ranks per region, including ties.
Worked solution
WITH context AS (SELECT region,day,net_cents,
SUM(net_cents) OVER (PARTITION BY region ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cumulative_cents,
LAG(net_cents) OVER (PARTITION BY region ORDER BY day) AS previous_net,
LAG(day) OVER (PARTITION BY region ORDER BY day) AS previous_day,
RANK() OVER (PARTITION BY region ORDER BY net_cents DESC) AS score_rank
FROM regional_days) SELECT region,day,score_rank FROM context WHERE score_rank<=2 ORDER BY region,net_cents DESC,day;
North’s two 200-cent days share rank one; its 100-cent day ranks third. South has two distinct ranks. The cutoff therefore returns two rows per region in this fixture, but the general tie-inclusive policy does not promise that exact count.
Exercise 2
Display positive North days while retaining the negative day’s cumulative effect.
Worked solution
WITH context AS (SELECT region,day,net_cents,
SUM(net_cents) OVER (PARTITION BY region ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cumulative_cents,
LAG(net_cents) OVER (PARTITION BY region ORDER BY day) AS previous_net,
LAG(day) OVER (PARTITION BY region ORDER BY day) AS previous_day,
RANK() OVER (PARTITION BY region ORDER BY net_cents DESC) AS score_rank
FROM regional_days) SELECT day,cumulative_cents FROM context WHERE region='North' AND net_cents>0 ORDER BY day;
The last displayed total remains 450. The negative October third row is hidden only after it contributes to the inner calculation. This preserves the declared full-history net measure.
Exercise 3
Report South’s adjacent-observation change together with elapsed calendar days.
Worked solution
WITH context AS (SELECT region,day,net_cents,
SUM(net_cents) OVER (PARTITION BY region ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cumulative_cents,
LAG(net_cents) OVER (PARTITION BY region ORDER BY day) AS previous_net,
LAG(day) OVER (PARTITION BY region ORDER BY day) AS previous_day,
RANK() OVER (PARTITION BY region ORDER BY net_cents DESC) AS score_rank
FROM regional_days) SELECT day,net_cents-previous_net,julianday(day)-julianday(previous_day) FROM context WHERE region='South' ORDER BY day;
The first row has no prior context. The second rises by forty cents across two days. A label such as one-day growth would be unsupported by this observation sequence.
Exercise 4
Reconcile source totals and confirm the report row count.
Worked solution
SELECT region,SUM(net_cents) FROM regional_days GROUP BY region ORDER BY region;
WITH context AS (SELECT region,day,net_cents,
SUM(net_cents) OVER (PARTITION BY region ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cumulative_cents,
LAG(net_cents) OVER (PARTITION BY region ORDER BY day) AS previous_net,
LAG(day) OVER (PARTITION BY region ORDER BY day) AS previous_day,
RANK() OVER (PARTITION BY region ORDER BY net_cents DESC) AS score_rank
FROM regional_days) SELECT COUNT(*) FROM context;
The grouped totals match the ending cumulative values, and six detail rows remain. These checks complement the event-level output; matching totals alone would not detect every wrong intermediate order or mislabeled prior comparison.
Knowledge check
Question 1
Why can North’s cumulative value decrease?
- SUM automatically resets on the third row
- The window excludes the current negative day
- The default frame forgets earlier days after a tie
- A valid negative net day is included
Answer and explanation
D. Cumulative net value reflects signed contributions.
Question 2
Why use different windows for ranking and cumulative totals?
- SQLite forbids reusing window names
- Their ordering questions differ
- The selected frame changes the sign of daily totals
- A rank must use the final display ordering in every query
Answer and explanation
B. Score order and chronological order express different analyses.
Question 3
What does South’s forty-cent change compare?
- October third with the previous recorded day, October first
- October third with an invented zero on October second
- Every South day with North
- Only the two best-ranked regions
Answer and explanation
A. LAG follows recorded row adjacency.
Question 4
Why filter positive days outside the context CTE?
- To remove negative days from both the window input and the display
- To make equal daily values receive different ranks
- To recompute every regional total using only positive days
- To preserve negative contributions in later cumulative values
Answer and explanation
D. Display filtering should not redefine the stated calculation history.
Question 5
Why avoid summing cumulative values?
- Each cumulative value represents only that day’s net change
- Summing cumulative values automatically subtracts the opening balance
- Earlier contributions would be counted repeatedly
- SUM removes contributions shared by successive cumulative values
Answer and explanation
C. A cumulative column is not an additive daily measure.
Pitfalls and summary
Do not combine windows by habit or label adjacent-observation changes as daily changes without checking gaps. Preserve the declared population, order, and frame for each measure. Verify detailed edge cases and independent totals, then describe the report’s scope honestly. Correct arithmetic needs correct interpretation.
SQLite behavior and references
Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.
Primary references
- SQLite window functions: Frames, offsets, ranking, and query placement
- SQLite date functions: Julian-day arithmetic on controlled dates