Total Orders per CustomerEasy

Total Orders per Customer

EasySQLPractice library · +10 XPaggregatessqlgroup by

Imagine you are working for an e-commerce company. You have a table containing information about customer orders.

  • orders (order_id integer, customer_id integer, order_date date, total_amount numeric(10,2))

Return the customer_id and the total number of orders placed by each customer. The results should be ordered by customer_id.

If a customer has no orders, they should not appear in the result. Ties in customer_id are not possible as it is a primary grouping key. NULL values in customer_id are not expected. Empty results are possible if the table is empty.

Tables

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    customer_id integer NOT NULL,
    order_date date NOT NULL,
    total_amount numeric(10,2) NOT NULL
);

Example data

INSERT INTO orders (order_id, customer_id, order_date, total_amount)
VALUES
(1, 101, '2023-01-15', 150.75),
(2, 102, '2023-01-16', 75.50),
(3, 101, '2023-01-17', 200.00),
(4, 103, '2023-01-18', 50.25),
(5, 101, '2023-01-19', 120.00),
(6, 102, '2023-01-20', 90.00),
(7, 104, '2023-01-21', 300.00),
(8, 103, '2023-01-22', 80.00);

Your query is also checked on hidden datasets with different data.

Hints