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:
Step 1: Use SUM() as window function
SUM(sales) OVER (ORDER BY date) calculates running total ordered by date.
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.
Final Answer:
SELECT date, sales, SUM(sales) OVER (ORDER BY date) AS cumulative_sales FROM sales_data; -> Option A
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
Master "Window Functions in PostgreSQL" in PostgreSQL
9 interactive learning modes - each teaches the same concept differently