You want to find the cumulative count of orders per customer ordered by order date. Which query correctly uses COUNT as a window function to achieve this?
hard📝 Application Q15 of 15
PostgreSQL - Window Functions in PostgreSQL
You want to find the cumulative count of orders per customer ordered by order date. Which query correctly uses COUNT as a window function to achieve this?
ASELECT customer_id, order_date, COUNT(*) FROM orders GROUP BY customer_id, order_date ORDER BY order_date;
BSELECT customer_id, order_date, COUNT(*) OVER (ORDER BY order_date) AS cumulative_orders FROM orders;
CSELECT customer_id, order_date, COUNT(*) OVER (PARTITION BY customer_id ORDER BY order_date) AS cumulative_orders FROM orders;
DSELECT customer_id, order_date, COUNT(*) OVER (PARTITION BY order_date ORDER BY customer_id) AS cumulative_orders FROM orders;
Step-by-Step Solution
Solution:
Step 1: Understand cumulative count per customer
COUNT(*) OVER (PARTITION BY customer_id ORDER BY order_date) counts rows per customer in order of order_date cumulatively.
Step 2: Check other options for correctness
SELECT customer_id, order_date, COUNT(*) FROM orders GROUP BY customer_id, order_date ORDER BY order_date; uses GROUP BY, not cumulative count; C lacks partition by customer; D partitions by order_date, not customer.
Final Answer:
SELECT customer_id, order_date, COUNT(*) OVER (PARTITION BY customer_id ORDER BY order_date) AS cumulative_orders FROM orders; -> Option C
Quick Check:
Use PARTITION BY customer_id with ORDER BY for cumulative count [OK]
Quick Trick:Partition by customer and order by date for cumulative count [OK]
Common Mistakes:
Missing PARTITION BY customer_id
Using GROUP BY instead of window function
Partitioning by wrong column
Master "Window Functions in PostgreSQL" in PostgreSQL
9 interactive learning modes - each teaches the same concept differently