opyeb QueryDeck

Window functions: ranks, running totals and moving averages

2026-11-28 · 2 min read

GROUP BY folds rows into one; a window function keeps every row and attaches the calculation beside it. That single difference makes ranking and running totals straightforward.

OVER defines the window

Adding OVER (...) makes a function compute over a subset: OVER () is the whole table, OVER (PARTITION BY channel) restarts per channel, and ORDER BY inside the parentheses sets the sequence.

SELECT order_id, channel, revenue,
       ROW_NUMBER() OVER (PARTITION BY channel ORDER BY revenue DESC) AS rn
FROM orders
ORDER BY channel, rn
LIMIT 12;

Three ranking functions

ROW_NUMBER gives unique numbers even for ties (1, 2, 3). RANK shares a rank on ties and skips the next (1, 1, 3). DENSE_RANK shares but does not skip (1, 1, 2). The choice is a statement about how ties should be read.

ValueROW_NUMBERRANKDENSE_RANK
100111
100211
90332
80443

Running totals and moving averages

SUM(revenue) OVER (ORDER BY order_date) is cumulative revenue to that date. ROWS BETWEEN 6 PRECEDING AND CURRENT ROW turns it into a seven-day total. Always state the frame: the default varies and is easy to misread.

SELECT session_date,
       COUNT(*) AS sessions,
       SUM(COUNT(*)) OVER (ORDER BY session_date) AS running_total,
       ROUND(AVG(COUNT(*)) OVER (ORDER BY session_date
             ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 1) AS avg_7d
FROM sessions
GROUP BY session_date
ORDER BY session_date;

Combining with GROUP BY

Window functions run after grouping, so you can rank groups or accumulate their totals. WHERE cannot see a window function, so wrap the query in a subquery and filter outside it.

Always state the frame

Without an explicit frame the database applies a default that depends on whether ORDER BY is present. Write ROWS BETWEEN ... AND ... for running totals and moving averages so the result is predictable.

Questions

Window function or GROUP BY?

GROUP BY returns one row per group; a window function keeps every row. They combine well.

Can PARTITION BY take several columns?

Yes. PARTITION BY channel, region restarts per combination.

Sources

Every query in this guide runs against the built-in sample data.

Open the lab