Skill 1.3.2
Write queries that include window functions
Key Concepts
The OVER clause defines the window: PARTITION BY splits rows into groups, ORDER BY orders them, and a frame such as ROWS BETWEEN 6 PRECEDING AND CURRENT ROW limits the rows an aggregate sees. Ranking functions include ROW_NUMBER (unique numbers), RANK (gaps after ties), DENSE_RANK (no gaps) and NTILE(n) (n buckets). Aggregates such as SUM and AVG with OVER produce running totals and moving averages.
Offset functions LAG and LEAD read a value from a previous or following row, and FIRST_VALUE and LAST_VALUE read the edges of the frame. Window functions cannot appear in WHERE, so a common pattern computes them in a CTE and filters outside, for example WHERE rn <= 3 for the top three rows per group. When ORDER BY is given without a frame, the default frame is RANGE UNBOUNDED PRECEDING, which treats ties together and is slower than an explicit ROWS frame.