Using PARTITION BY for Grouping Windows in PostgreSQL
📖 Scenario: You work at a bookstore that tracks sales data. You want to analyze sales by each book category to see how each sale compares within its category.
🎯 Goal: Build a PostgreSQL query that uses PARTITION BY to group sales by book category and calculate the running total of sales within each category.
📋 What You'll Learn
Create a table called
book_sales with columns sale_id, category, and amount.Insert the exact sales data provided into
book_sales.Write a query that uses
SUM(amount) OVER (PARTITION BY category ORDER BY sale_id) to calculate running totals per category.Select
sale_id, category, amount, and the running total as running_total.💡 Why This Matters
🌍 Real World
Analyzing sales data by category helps businesses understand performance trends within each group.
💼 Career
Using window functions with PARTITION BY is a common skill for data analysts and database developers to perform advanced data analysis.
Progress0 / 4 steps