Introduction
We use GROUP BY multiple columns to organize data into groups based on more than one category. This helps us see patterns or summaries for combinations of values.
Jump into concepts and practice - no test required
We use GROUP BY multiple columns to organize data into groups based on more than one category. This helps us see patterns or summaries for combinations of values.
SELECT column1, column2, aggregate_function(column3) FROM table_name GROUP BY column1, column2;
SELECT city, product, COUNT(*) FROM sales GROUP BY city, product;
SELECT department, job_title, AVG(salary) FROM employees GROUP BY department, job_title;
SELECT year, month, SUM(expense) FROM expenses GROUP BY year, month;
This example creates a sales table, inserts some data, then groups the sales by store and product to find total quantity sold for each group.
CREATE TABLE sales ( store VARCHAR(20), product VARCHAR(20), quantity INT ); INSERT INTO sales VALUES ('StoreA', 'Apples', 10), ('StoreA', 'Oranges', 5), ('StoreB', 'Apples', 7), ('StoreB', 'Oranges', 3), ('StoreA', 'Apples', 2); SELECT store, product, SUM(quantity) AS total_quantity FROM sales GROUP BY store, product ORDER BY store, product;
Always include all non-aggregated columns in the GROUP BY clause.
You can group by as many columns as you need to get detailed summaries.
Ordering results after grouping helps read the output clearly.
GROUP BY multiple columns groups data by combinations of those columns.
Use it to get summaries like counts or sums for each group.
Remember to include all grouped columns in SELECT and GROUP BY.
GROUP BY column1, column2 do?city and year?sales with columns region, product, and amount, what will this query return?SELECT region, product, SUM(amount) FROM sales GROUP BY region, product;
SELECT department, role, COUNT(*) FROM employees GROUP BY department;
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?