Total Orders per Customer
Imagine you are working for an e-commerce company. You have a table containing information about customer orders.
- orders (
order_idinteger,customer_idinteger,order_datedate,total_amountnumeric(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
-- Select the customer_id and count of orders for each customer
SELECT customer_id, COUNT(order_id)
FROM orders
Your query runs on the example tables shown with the problem, then on hidden datasets when you submit.
Write standard SQL. MySQL habits work too: IFNULL, IF, YEAR(), DATE_FORMAT, GROUP_CONCAT, `backticks` and LIMIT 5, 10. It runs on PostgreSQL, so integer division keeps whole numbers (5 / 2 = 2): write 5.0 / 2 for 2.5.