SQL

Counting Related Records with JOIN and GROUP BY

Discover how to combine data from multiple tables and aggregate counts of related records, such as the number of orders per customer, using SQL JOINs and GROUP BY clauses.

SELECT
    c.customer_id,
    c.customer_name,
    COUNT(o.order_id) AS total_orders
FROM
    customers c
LEFT JOIN
    orders o ON c.customer_id = o.customer_id
GROUP BY
    c.customer_id, c.customer_name
HAVING
    COUNT(o.order_id) > 0
ORDER BY
    total_orders DESC;
How it works: This query joins the `customers` table with the `orders` table to count the total number of orders placed by each customer. The `LEFT JOIN` ensures that all customers are considered, even those without orders. `GROUP BY` aggregates the counts for each unique customer. The `HAVING` clause then filters these groups to only include customers who have placed at least one order, and the results are ordered by the total number of orders.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs