Using Named Windows with WINDOW Clause in PostgreSQL
📖 Scenario: You work in a sales department and want to analyze monthly sales data for different salespeople. You want to calculate running totals and averages over specific time frames without repeating the same window definitions multiple times.
🎯 Goal: Build a SQL query that uses the WINDOW clause to define named windows and then use those named windows in OVER clauses to calculate running totals and averages.
📋 What You'll Learn
Create a table called
sales with columns salesperson (text), month (integer), and amount (integer).Insert the exact sales data for three salespeople over three months.
Define a named window called
monthly_window that partitions by salesperson and orders by month.Use the named window
monthly_window to calculate a running total of amount.Use the named window
monthly_window to calculate a running average of amount.💡 Why This Matters
🌍 Real World
Sales analysts often need to calculate running totals and averages over time for each salesperson to track performance trends.
💼 Career
Knowing how to use named windows in SQL is useful for writing efficient and readable analytical queries in business intelligence and data analysis roles.
Progress0 / 4 steps