ANN Technologies Logo
ANN Technologies brand mark ANN Technologies Find your spark

Analytical SQL Patterns: Window Functions and Advanced Aggregations

Window functions are the most powerful SQL feature most analysts never master. Learn how to calculate running totals, rankings, moving averages, and period-over-period comparisons.

Why Window Functions?

Window functions perform calculations across a set of rows related to the current row — without collapsing the result set like GROUP BY. They enable sophisticated analytics that would otherwise require self-joins or subqueries.

Common Patterns

-- Running total of revenuenSELECTn  date,n  revenue,n  SUM(revenue) OVER (ORDER BY date ROWS UNBOUNDED PRECEDING) AS running_totalnFROM sales;nn-- 7-day moving averagenSELECTn  date,n  AVG(revenue) OVER (ORDER BY date ROWS 6 PRECEDING) AS moving_avg_7dnFROM sales;nn-- Rank customers by revenue within each regionnSELECTn  region, customer_id, revenue,n  RANK() OVER (PARTITION BY region ORDER BY revenue DESC) AS ranknFROM customers;