Bird
0
0

How do you write a PostgreSQL query to compute a cumulative sum of sales ordered by date using a window function?

easy📝 Syntax Q3 of 15
PostgreSQL - Window Functions in PostgreSQL
How do you write a PostgreSQL query to compute a cumulative sum of sales ordered by date using a window function?
ASELECT date, sales, SUM(sales) OVER (ORDER BY date) AS cumulative_sales FROM sales_data;
BSELECT date, sales, SUM(sales) GROUP BY date ORDER BY date;
CSELECT date, sales, SUM(sales) FROM sales_data WINDOW ORDER BY date;
DSELECT date, sales, SUM(sales) PARTITION BY date ORDER BY sales;
Step-by-Step Solution
Solution:
  1. Step 1: Use SUM() as window function

    SUM(sales) OVER (ORDER BY date) calculates running total ordered by date.
  2. Step 2: Check syntax correctness

    SELECT date, sales, SUM(sales) OVER (ORDER BY date) AS cumulative_sales FROM sales_data; uses correct OVER clause syntax with ORDER BY inside parentheses.
  3. Final Answer:

    SELECT date, sales, SUM(sales) OVER (ORDER BY date) AS cumulative_sales FROM sales_data; -> Option A
  4. Quick Check:

    SUM() OVER (ORDER BY ...) computes running totals [OK]
Quick Trick: Use SUM() OVER (ORDER BY column) for running totals [OK]
Common Mistakes:
  • Using GROUP BY instead of window function
  • Incorrect OVER clause syntax
  • Misplacing PARTITION BY when not needed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes