BBampaa

Lessons › SQL › Chapter 3: Summarising

SQL lesson

GROUP BY with multiple columns

GROUP BY with multiple columns splits results into finer slices by combining two or more grouping criteria at once, giving you a separate total for every unique combination.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Breaking Down Retail Results with GROUP BY on Multiple Columns

SELECT category, region, SUM(revenue) AS total_revenue
FROM orders
GROUP BY category, region
ORDER BY category, region

Result:

categoryregiontotal_revenue
ClothingNorth89.99
ClothingSouth134.75
ElectronicsNorth730.0
ElectronicsSouth215.5

Step by step

  1. Run the query without SUM so you can see what the unfiltered values look like.
    SELECT category, region, revenue
    FROM orders
    GROUP BY category, region
    ORDER BY category, region;
  2. SUM totals the numbers in a column. Works on numeric columns only.
    SELECT category, region, SUM(revenue)
    FROM orders
    GROUP BY category, region
    ORDER BY category, region;
  3. AS gives the SUM result a friendly column name so the output reads cleanly.
    SELECT category, region, SUM(revenue) AS total_revenue
    FROM orders
    GROUP BY category, region
    ORDER BY category, region;

Practice

Try each one in your head first, then open the answer.

1. Using orders, write a query to count rows for each combination of order_id and customer_id.
SELECT order_id, customer_id, COUNT(*) FROM orders GROUP BY order_id, customer_id
2. Using store_sales, write a query to count rows for each combination of sale_id and store_id.
SELECT sale_id, store_id, COUNT(*) FROM store_sales GROUP BY sale_id, store_id
3. Using products, write a query to count rows for each combination of product_id and brand.
SELECT product_id, brand, COUNT(*) FROM products GROUP BY product_id, brand
4. Using reviews, write a query to count rows for each combination of review_id and product_id.
SELECT review_id, product_id, COUNT(*) FROM reviews GROUP BY review_id, product_id
5. Using employees, write a query to count rows for each combination of employee_id and full_name.
SELECT employee_id, full_name, COUNT(*) FROM employees GROUP BY employee_id, full_name

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed