Window functions represent the pinnacle of analytical SQL. They allow data scientists to compute running totals, rolling averages, rankings, and lead/lag differences across partitions without messy self-joins or row collapsing.
-- Query: Identify the Top 3 revenue-generating products per category and compute MoM growth
WITH MonthlyProductRevenue AS (
SELECT
p.category_name,
p.product_name,
DATE_TRUNC('month', o.order_date) AS order_month,
SUM(oi.quantity * oi.unit_price) AS monthly_sales
FROM products p
JOIN order_items oi ON p.product_id = oi.product_id
JOIN orders o ON oi.order_id = o.order_id
GROUP BY p.category_name, p.product_name, DATE_TRUNC('month', o.order_date)
),
RankedProducts AS (
SELECT
category_name,
product_name,
order_month,
monthly_sales,
-- Rank within category partition
DENSE_RANK() OVER (
PARTITION BY category_name, order_month
ORDER BY monthly_sales DESC
) AS sales_rank,
-- Previous month's sales via LAG
LAG(monthly_sales, 1) OVER (
PARTITION BY category_name, product_name
ORDER BY order_month
) AS prev_month_sales
FROM MonthlyProductRevenue
)
SELECT
category_name,
product_name,
order_month,
monthly_sales,
sales_rank,
ROUND(
(monthly_sales - prev_month_sales) / NULLIF(prev_month_sales, 0) * 100.0, 2
) AS mom_growth_pct
FROM RankedProducts
WHERE sales_rank <= 3
ORDER BY category_name, order_month, sales_rank;
To smooth daily website traffic spikes, compute a 7-day moving average using: AVG(daily_visitors) OVER (ORDER BY visit_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS rolling_7d_avg.
Broaden your statistical analysis, Python data wrangling, and production engineering expertise:
Review fundamental SELECT queries, filtering, and table joins.
Put window functions into practice for user retention and churn analysis.
Execute distributed analytical window queries on terabyte datasets.
Solve the top 20 most frequent SQL coding challenges in technical interviews.