running total
🎯 Goal:
Calculate a running total of a column (like sales_amount
) using:
-
✅ Self Join
-
✅ Window Function (modern/easier way)
Let's assume a table: daily_sales
sale_date | sales_amount |
---|---|
2025-06-01 | 100 |
2025-06-02 | 120 |
2025-06-03 | 130 |
2025-06-04 | 110 |
🔁 1. Running Total Using Self Join (Old School SQL)
🔍 How it works:
-
For each row
a
, join all rowsb
that occurred on or beforea.sale_date
-
Then sum all
b.sales_amount
⚡ 2. Running Total Using Window Function (Modern SQL)
✅ Simpler, faster, and more readable.
Works in: PostgreSQL, SQL Server, Oracle, MySQL 8+, etc.
📊 Sample Output:
sale_date | sales_amount | running_total |
---|---|---|
2025-06-01 | 100 | 100 |
2025-06-02 | 120 | 220 |
2025-06-03 | 130 | 350 |
2025-06-04 | 110 | 460 |
Comments
Post a Comment