How can you use multiple CTEs to first select orders with amount > 200, then compute total sales per customer?
hard📝 Application Q9 of 15
PostgreSQL - Common Table Expressions
How can you use multiple CTEs to first select orders with amount > 200, then compute total sales per customer?
AWITH filtered_orders AS (SELECT * FROM orders WHERE amount > 200), total_sales AS (SELECT customer_id, SUM(amount) AS total FROM filtered_orders GROUP BY customer_id) SELECT * FROM total_sales;
BWITH total_sales AS (SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id), filtered_orders AS (SELECT * FROM total_sales WHERE total > 200) SELECT * FROM filtered_orders;
CWITH filtered_orders AS (SELECT * FROM orders WHERE amount > 200) SELECT customer_id, SUM(amount) AS total FROM filtered_orders;
DWITH total_sales AS (SELECT customer_id, SUM(amount) AS total FROM orders WHERE amount > 200 GROUP BY customer_id) SELECT * FROM total_sales;
Step-by-Step Solution
Solution:
Step 1: Filter orders
First CTE filters orders with amount > 200.
Step 2: Aggregate sales
Second CTE sums amounts per customer from filtered orders.
Step 3: Final select
Query selects all from total_sales CTE.
Final Answer:
Option A -> Option A
Quick Check:
Filter first, then aggregate [OK]
Quick Trick:Filter before aggregation in CTEs [OK]
Common Mistakes:
Aggregating before filtering
Filtering aggregated results incorrectly
Not grouping by customer_id
Master "Common Table Expressions" in PostgreSQL
9 interactive learning modes - each teaches the same concept differently