Bird
0
0

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:
  1. Step 1: Understand running total requirement

    Calculate cumulative sum per customer ordered by sale date, showing each sale.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes