Which SQL query correctly groups data by columns category and year?
easy📝 Syntax Q3 of 15
SQL - GROUP BY and HAVING
Which SQL query correctly groups data by columns category and year?
ASELECT category, year, COUNT(*) FROM sales GROUP BY year;
BSELECT category, year, COUNT(*) FROM sales GROUP BY category, year;
CSELECT category, year, COUNT(*) FROM sales GROUP BY category;
DSELECT category, year, COUNT(*) FROM sales ORDER BY category, year;
Step-by-Step Solution
Solution:
Step 1: Identify correct GROUP BY syntax
The query must group by both category and year to aggregate correctly.
Step 2: Check each option
SELECT category, year, COUNT(*) FROM sales GROUP BY category, year; groups by both columns, matching the SELECT list. Options A and B group by only one column, causing errors or wrong results. SELECT category, year, COUNT(*) FROM sales ORDER BY category, year; uses ORDER BY, not GROUP BY.
Final Answer:
SELECT category, year, COUNT(*) FROM sales GROUP BY category, year; -> Option B
Quick Check:
GROUP BY columns must match SELECT columns for aggregation [OK]
Quick Trick:GROUP BY columns must match SELECT columns with aggregates [OK]
Common Mistakes:
MISTAKES
Grouping by fewer columns than selected
Using ORDER BY instead of GROUP BY
Missing commas in GROUP BY clause
Master "GROUP BY and HAVING" in SQL
9 interactive learning modes - each teaches the same concept differently