Skip to content
PostgreSQL

Window Functions

Compute rankings, running totals, and moving averages.

#window#analytics#ranking

Code

postgresql
-- Rank orders by amount per customer
SELECT customer_id, id, total,
       RANK() OVER (PARTITION BY customer_id ORDER BY total DESC) AS rnk
FROM orders;

-- Running total and moving average
SELECT created_at::date AS day,
       SUM(total) AS daily,
       SUM(SUM(total)) OVER (ORDER BY created_at::date) AS running,
       AVG(SUM(total)) OVER (
         ORDER BY created_at::date
         ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
       ) AS rolling_7d
FROM orders
GROUP BY created_at::date
ORDER BY day;

-- LAG and LEAD for period-over-period
SELECT day, daily,
       LAG(daily, 7) OVER (ORDER BY day) AS prev_week
FROM daily_stats;