What are window functions?#
A window function performs a calculation across a set of rows related to the current row - without collapsing them into one row like GROUP BY does.
function_name(...) OVER (
PARTITION BY column -- optional: restart for each group
ORDER BY column -- optional: order within the window
)
Every product row is kept, and each gets its category's average next to it - impossible with a simple GROUP BY.
Window function = हर row के साथ उसके "आस-पास के समूह" (window) की calculation जोड़ना - rows को मिलाए बिना।
GROUP BY में हर category की एक row बचती है। Window function में सारी rows रहती हैं और हर row के आगे उसकी category का औसत, rank, running total आदि लिख दिया जाता है।
PARTITION BY= किस समूह में calculation करनी है (हर category अलग)ORDER BY(OVER के अंदर) = rank या running total किस क्रम में
Ranking functions#
| Function | Ties (100, 90, 90, 80) | Use |
|---|---|---|
ROW_NUMBER() |
1, 2, 3, 4 | unique numbering, "pick one per group" |
RANK() |
1, 2, 2, 4 | competition ranking (gaps after ties) |
DENSE_RANK() |
1, 2, 2, 3 | ranking without gaps |
NTILE(4) |
quartile 1-4 | split into equal buckets |
Top N per group#
Window functions can't go directly in WHERE - compute them in a CTE first:
Aggregate window functions#
SUM, AVG, COUNT, MIN, MAX all work with OVER.
Percentage of total#
OVER () with nothing inside = the window is all rows of the result.
Running total#
Moving average#
A frame clause limits the window to nearby rows:
AVG(revenue) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) -- 3-month moving average
LAG and LEAD - comparing with previous/next rows#
LAG(col, n, default)- value n rows before (default n = 1).LEAD(col, n, default)- value n rows after.- Month-on-month growth % =
(x - LAG(x)) * 100.0 / LAG(x).
Customer behaviour: days between orders#
Window functions cheat sheet#
| Question | Window function |
|---|---|
| Rank products by sales | RANK() OVER (ORDER BY sales DESC) |
| Top 3 per region | ROW_NUMBER() OVER (PARTITION BY region ORDER BY sales DESC) + filter |
| % of total | x * 100.0 / SUM(x) OVER () |
| % within group | x * 100.0 / SUM(x) OVER (PARTITION BY group) |
| Running total | SUM(x) OVER (ORDER BY date) |
| Moving average | AVG(x) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) |
| Month-on-month change | x - LAG(x) OVER (ORDER BY month) |
| First purchase date per customer | MIN(order_date) OVER (PARTITION BY customer_id) |
Summary#
- Window functions calculate across related rows and keep every row:
f() OVER (PARTITION BY ... ORDER BY ...). - Ranking: ROW_NUMBER, RANK, DENSE_RANK, NTILE; filter top-N in a CTE.
- Aggregates over windows give % of total, running totals and moving averages.
- LAG and LEAD compare a row with previous/next rows - growth, gaps, trends.