Mrs. Tini’s ledger: running balances, ranks and each row’s window frame from a real SQLite, with GROUP BY beside it. 12 rows in: how many come out of each? An…
Why it matters
Window functions answer "rank within each group", "running balance" and "compared with the row before" without a slow self-join. What trips people up: the default frame taking peers along, RANK with no ORDER BY, and a window alias that WHERE cannot use.
The key idea
Every row has its own window, and the rows stay whole
Common mistakes
Want a rank per row but afraid the rows vanish as with GROUP BY A window function folds no rows, it only adds a column: 12 in, 12 out. GROUP BY answers another question (one row per group).
Filtering on a window function’s alias in WHERE errors The window is worked out after WHERE, so its alias does not exist yet (SQLite: "misuse of aliased window function"). Wrap it in a subquery or CTE, then filter in the outer query.
RANK() feels random, with no clear order The ORDER BY inside OVER() is missing. Without it every row of a partition is a peer: RANK gives them all 1, ROW_NUMBER numbers them in any order.
Try it in this playground
Compare RANK, DENSE_RANK and ROW_NUMBER Use two of them on the tied deposits: see how they number.
Set a ROWS frame Write a frame for SUM or AVG: the orange bracket in the book changes with it.
Filter the window’s result in an outer query Turn on "Filter in the outer query" with a WHERE on hasil.
Walk through three rows Move to other rows: each row has its own window.