Using the OVER Clause with ORDER BY in SQL
📖 Scenario: You work in a sales department and have a table of monthly sales data for different salespeople. You want to calculate a running total of sales for each salesperson ordered by month.
🎯 Goal: Build a SQL query that uses the OVER clause with ORDER BY to calculate a running total of sales per salesperson ordered by month.
📋 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.
Write a query that selects
salesperson, month, amount, and a running total of amount using SUM(amount) OVER (PARTITION BY salesperson ORDER BY month).Order the final query result by
salesperson and month.💡 Why This Matters
🌍 Real World
Running totals are common in sales reports, financial statements, and time series analysis to track cumulative progress over time.
💼 Career
Knowing how to use window functions like OVER with ORDER BY is essential for data analysts and database developers to write efficient and insightful queries.
Progress0 / 4 steps