Bird
0
0

Which query correctly achieves this?

hard📝 Application Q15 of 15
SQL - GROUP BY and HAVING
You have a transactions table with columns customer_id, month, and amount. You want to find the average transaction amount per customer per month, but only for months where the customer made more than 3 transactions. Which query correctly achieves this?
ASELECT customer_id, month, AVG(amount) FROM transactions GROUP BY customer_id, month HAVING COUNT(*) > 3;
BSELECT customer_id, month, AVG(amount) FROM transactions WHERE COUNT(*) > 3 GROUP BY customer_id, month;
CSELECT customer_id, month, AVG(amount) FROM transactions GROUP BY customer_id HAVING COUNT(*) > 3;
DSELECT customer_id, month, AVG(amount) FROM transactions GROUP BY month HAVING COUNT(*) > 3;
Step-by-Step Solution
Solution:
  1. Step 1: Understand filtering groups with HAVING

    HAVING filters groups after grouping. To filter groups with more than 3 transactions, use HAVING COUNT(*) > 3.
  2. Step 2: Group by both customer_id and month

    To get average per customer per month, group by both columns.
  3. Step 3: Check each option

    SELECT customer_id, month, AVG(amount) FROM transactions GROUP BY customer_id, month HAVING COUNT(*) > 3; correctly uses GROUP BY customer_id, month and HAVING COUNT(*) > 3. SELECT customer_id, month, AVG(amount) FROM transactions WHERE COUNT(*) > 3 GROUP BY customer_id, month; misuses WHERE with COUNT(). SELECT customer_id, month, AVG(amount) FROM transactions GROUP BY customer_id HAVING COUNT(*) > 3; groups only by customer_id, missing month. SELECT customer_id, month, AVG(amount) FROM transactions GROUP BY month HAVING COUNT(*) > 3; groups only by month, missing customer_id.
  4. Final Answer:

    SELECT customer_id, month, AVG(amount) FROM transactions GROUP BY customer_id, month HAVING COUNT(*) > 3; -> Option A
  5. Quick Check:

    Use HAVING to filter grouped counts [OK]
Quick Trick: Use HAVING to filter groups after GROUP BY [OK]
Common Mistakes:
MISTAKES
  • Using WHERE with aggregate functions
  • Grouping by only one column when two needed
  • Filtering before grouping instead of after

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes