How would you write a query to compute a running total of sales per customer, while still displaying each individual sale record?
hard📝 Application Q9 of 15
SQL - Window Functions Fundamentals
How would you write a query to compute a running total of sales per customer, while still displaying each individual sale record?
ASELECT customer_id, sale_amount, SUM(sale_amount) OVER (PARTITION BY customer_id ORDER BY sale_date) AS running_total FROM sales;
BSELECT customer_id, SUM(sale_amount) FROM sales GROUP BY customer_id ORDER BY sale_date;
CSELECT customer_id, sale_amount, SUM(sale_amount) FROM sales GROUP BY customer_id, sale_date;
DSELECT customer_id, sale_amount, SUM(sale_amount) FROM sales;
Step-by-Step Solution
Solution:
Step 1: Understand running total requirement
Calculate cumulative sum per customer ordered by sale date, showing each sale.
Step 2: Analyze options
SELECT customer_id, sale_amount, SUM(sale_amount) OVER (PARTITION BY customer_id ORDER BY sale_date) AS running_total FROM sales; uses a window function with PARTITION BY customer_id and ORDER BY sale_date, which computes running total per customer without collapsing rows.
Step 3: Why others are incorrect
Options B, C, and D use GROUP BY or no window function, which aggregate rows and lose individual sale details.
Final Answer:
SELECT customer_id, sale_amount, SUM(sale_amount) OVER (PARTITION BY customer_id ORDER BY sale_date) AS running_total FROM sales; correctly computes running total while preserving rows.
Quick Check:
Window functions with ORDER BY enable running totals. [OK]
Quick Trick:Use window SUM() OVER with ORDER BY for running totals. [OK]
Common Mistakes:
Using GROUP BY which collapses rows.
Omitting ORDER BY in window function.
Not partitioning by customer.
Master "Window Functions Fundamentals" in SQL
9 interactive learning modes - each teaches the same concept differently