Bird
0
0

You want to find customers who placed orders totaling more than 500, but only include those customers who have placed at least 3 orders. Which CTE-based query correctly achieves this?

hard📝 Application Q15 of 15
SQL - Common Table Expressions (CTEs)
You want to find customers who placed orders totaling more than 500, but only include those customers who have placed at least 3 orders. Which CTE-based query correctly achieves this?
AWITH order_summary AS ( SELECT customer_id, COUNT(order_id) AS order_count FROM orders GROUP BY customer_id HAVING COUNT(order_id) >= 3 ) SELECT * FROM order_summary WHERE total_amount > 500;
BWITH order_summary AS ( SELECT customer_id, SUM(amount) AS total_amount FROM orders GROUP BY customer_id HAVING SUM(amount) > 500 ) SELECT * FROM order_summary WHERE order_count >= 3;
CWITH order_summary AS ( SELECT customer_id, COUNT(order_id) AS order_count, SUM(amount) AS total_amount FROM orders GROUP BY customer_id HAVING SUM(amount) > 500 AND COUNT(order_id) >= 3 ) SELECT * FROM order_summary;
DWITH order_summary AS ( SELECT customer_id, SUM(amount) AS total_amount FROM orders GROUP BY customer_id ) SELECT * FROM order_summary WHERE total_amount > 500 AND order_count >= 3;
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirements

    We need customers with total order amount > 500 and at least 3 orders.
  2. Step 2: Check each option's logic

    WITH order_summary AS ( SELECT customer_id, COUNT(order_id) AS order_count, SUM(amount) AS total_amount FROM orders GROUP BY customer_id HAVING SUM(amount) > 500 AND COUNT(order_id) >= 3 ) SELECT * FROM order_summary; calculates both count and sum in the CTE and filters with HAVING both conditions, which is correct. Options B, C, and D try to filter outside the CTE on columns not selected or missing.
  3. Final Answer:

    WITH order_summary AS ( SELECT customer_id, COUNT(order_id) AS order_count, SUM(amount) AS total_amount FROM orders GROUP BY customer_id HAVING SUM(amount) > 500 AND COUNT(order_id) >= 3 ) SELECT * FROM order_summary; -> Option C
  4. Quick Check:

    Filter both conditions inside CTE HAVING = A [OK]
Quick Trick: Use HAVING to filter grouped results inside CTE [OK]
Common Mistakes:
  • Filtering aggregated columns outside CTE
  • Missing COUNT or SUM in CTE select
  • Using WHERE instead of HAVING for aggregates

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes