Using SUM, AVG, and COUNT as Window Functions in PostgreSQL
📖 Scenario: You work for a small online store. You have a table of sales records showing each sale's sale_id, customer_id, and amount. You want to analyze sales data by calculating running totals, average sales, and counts of sales per customer.
🎯 Goal: Build a PostgreSQL query that uses window functions SUM(), AVG(), and COUNT() to calculate running totals, average sale amounts, and total sales count per customer.
📋 What You'll Learn
Create a table called
sales with columns sale_id (integer), customer_id (integer), and amount (numeric).Insert exactly 5 rows into
sales with specified values.Write a query that uses
SUM(amount) OVER (PARTITION BY customer_id ORDER BY sale_id) to get running total per customer.Use
AVG(amount) OVER (PARTITION BY customer_id) to get average sale amount per customer.Use
COUNT(*) OVER (PARTITION BY customer_id) to get total number of sales per customer.💡 Why This Matters
🌍 Real World
Window functions help analyze data trends over groups without collapsing rows, useful in sales, finance, and reporting.
💼 Career
Understanding window functions is essential for data analysts and database developers to write efficient and insightful SQL queries.
Progress0 / 4 steps