Description

Table: Orders

Column NameType
order_numberint
customer_numberint
  • order_number is the primary key for this table.
  • This table contains information about the order ID and the customer ID.

Problem Statement

Write an SQL query to find the customer_number for the customer who has placed the largest number of orders.

The test cases are generated so that exactly one customer will have placed more orders than any other customer.

The query result format is in the following example.

Example 1:

Input:

  • Orders table
order_numbercustomer_number
11
22
33
43

Output:

customer_number
3

Explanation:

  • The customer with number 3 has two orders, which is greater than either customer 1 or 2 because each of them only has one order. So the result is customer_number 3.

Solution

This is simple aggregation problem where you have to find the number of orders by each customer, order the results in descending order and retrieve the first customer_number.

1SELECT customer_number
2    FROM Orders
3    GROUP BY customer_number
4    ORDER BY COUNT(order_number) DESC
5    LIMIT 1;

Notice, that we don’t need to include aggregation function in the result of the query. You can directly use it in the ORDER BY clause.