Skip to content
Laviyx Learn

Try

SQL GROUP BY Practice

Summarise data per group with COUNT, SUM and AVG, and filter groups with HAVING.

Beginner3 problemsUpdated

Review first: GROUP BY

All problems use this sales table:

sale_idregionproductquantityamount
1NorthLaptop2120000
2SouthPhone575000
3NorthPhone345000
4EastLaptop160000
5SouthTablet448000
6NorthTablet224000
Try your answers on these tables in the SQL Playground
  1. 1.Revenue per region

    Beginner

    Return each region and its total amount as revenue, highest revenue first.

    Show hint

    GROUP BY region, SUM(amount), then ORDER BY revenue DESC.

    Show solution
    SQLRun
    SELECT region, SUM(amount) AS revenue
    FROM sales
    GROUP BY region
    ORDER BY revenue DESC;
    Output
    region | revenue
    -------+--------
    North  | 189000
    South  | 123000
    East   | 60000
  2. 2.Units per product

    Beginner

    For each product, return the number of sales (sales_count) and the total units sold (units).

    Show hint

    Use COUNT(*) and SUM(quantity) together.

    Show solution
    SQLRun
    SELECT product,
           COUNT(*)      AS sales_count,
           SUM(quantity) AS units
    FROM sales
    GROUP BY product
    ORDER BY product;
    Output
    product | sales_count | units
    --------+-------------+------
    Laptop  | 2           | 3
    Phone   | 2           | 8
    Tablet  | 2           | 6
  3. 3.Busy regions

    Intermediate

    Return the regions that made more than one sale and whose average sale amount is above 50,000.

    Show hint

    Both conditions are about groups, so both go in HAVING.

    Show solution
    SQLRun
    SELECT region,
           COUNT(*)    AS sales_count,
           AVG(amount) AS avg_amount
    FROM sales
    GROUP BY region
    HAVING COUNT(*) > 1
       AND AVG(amount) > 50000;
    Output
    region | sales_count | avg_amount
    -------+-------------+-----------
    North  | 3           | 63000
    South  | 2           | 61500

    East has only one sale, so COUNT(*) > 1 removes it. North averages 189,000 / 3 = 63,000 and South averages 123,000 / 2 = 61,500.