You want to create a view that shows total sales per customer but only for customers with sales over 1000. Which approach correctly uses a view to achieve this?
hard📝 Application Q8 of 15
PostgreSQL - Views and Materialized Views
You want to create a view that shows total sales per customer but only for customers with sales over 1000. Which approach correctly uses a view to achieve this?
ACREATE VIEW high_sales AS SELECT customer_id, amount FROM sales WHERE amount > 1000;
BCREATE VIEW high_sales AS SELECT customer_id, SUM(amount) AS total FROM sales GROUP BY customer_id HAVING SUM(amount) > 1000;
CCREATE VIEW high_sales AS SELECT customer_id, SUM(amount) FROM sales WHERE amount > 1000;
DCREATE VIEW high_sales AS SELECT customer_id, SUM(amount) AS total FROM sales GROUP BY customer_id WHERE total > 1000;
Step-by-Step Solution
Solution:
Step 1: Use GROUP BY and HAVING to filter aggregated results
To get total sales per customer and filter by total, GROUP BY customer_id and HAVING SUM(amount) > 1000 is required.
Step 2: Check each option's correctness
CREATE VIEW high_sales AS SELECT customer_id, SUM(amount) AS total FROM sales GROUP BY customer_id HAVING SUM(amount) > 1000; correctly uses GROUP BY and HAVING; others misuse WHERE or omit GROUP BY.
Final Answer:
CREATE VIEW high_sales AS SELECT customer_id, SUM(amount) AS total FROM sales GROUP BY customer_id HAVING SUM(amount) > 1000; -> Option B
Quick Check:
Use HAVING to filter aggregates in views = A [OK]
Quick Trick:Use HAVING to filter grouped data in views [OK]
Common Mistakes:
Using WHERE instead of HAVING for aggregates
Omitting GROUP BY with SUM
Misplacing WHERE after GROUP BY
Master "Views and Materialized Views" in PostgreSQL
9 interactive learning modes - each teaches the same concept differently