Window Frame with ROWS BETWEEN and RANGE BETWEEN in PostgreSQL
📖 Scenario: You work for a sales company that tracks daily sales amounts for different stores. You want to analyze sales trends by calculating running totals and moving averages over specific ranges of days.
🎯 Goal: Build a PostgreSQL query that uses window functions with ROWS BETWEEN and RANGE BETWEEN frame clauses to calculate running totals and moving averages of sales amounts ordered by date.
📋 What You'll Learn
Create a table called
daily_sales with columns store_id (integer), sale_date (date), and amount (numeric).Insert the exact sales data for 3 stores over 5 consecutive days.
Write a query that calculates the running total of sales per store ordered by
sale_date using ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.Write a query that calculates the moving average of sales per store ordered by
sale_date using RANGE BETWEEN INTERVAL '2 days' PRECEDING AND CURRENT ROW.Use window functions with the correct partitioning and ordering.
💡 Why This Matters
🌍 Real World
Businesses often analyze sales data over time to understand trends and performance. Window functions with frame clauses help calculate running totals and moving averages efficiently.
💼 Career
Data analysts and database developers use window functions in SQL to write advanced queries for reporting and analytics.
Progress0 / 4 steps