Most reporting questions have the same shape: compare each row with others around it. "What's the running total?", "Which product ranked first each month?", "How did this month compare with last?" Window functions answer all of these in plain SQL.

The idea

A window function calculates across a set of rows related to the current row, without collapsing them like GROUP BY does. The OVER clause defines that set.

Running totals

SELECT sale_date, amount,
       SUM(amount) OVER (ORDER BY sale_date) AS running_total
FROM daily_sales;

Rankings within a group

SELECT month, product, revenue,
       RANK() OVER (PARTITION BY month ORDER BY revenue DESC) AS rank_in_month
FROM monthly_product_sales;

Filter with WHERE rank_in_month <= 3 in an outer query to get the top three products per month.

Change from the previous period

SELECT month, revenue,
       revenue - LAG(revenue) OVER (ORDER BY month) AS change,
       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
             / NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS pct_change
FROM monthly_revenue;

NULLIF avoids dividing by zero in the first month or any month with no revenue.

Moving averages

Daily figures are noisy. A seven-day average shows the trend:

AVG(amount) OVER (ORDER BY sale_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)

Why it matters

Doing this in SQL keeps the logic in one place. Every dashboard and export reads the same numbers, instead of each spreadsheet calculating its own slightly different version.