返回介绍

solution / 0500-0599 / 0586.Customer Placing the Largest Number of Orders / README_EN

发布于 2024-06-17 01:03:59 字数 2821 浏览 0 评论 0 收藏 0

586. Customer Placing the Largest Number of Orders

中文文档

Description

Table: Orders

+-----------------+----------+
| Column Name   | Type   |
+-----------------+----------+
| order_number  | int    |
| customer_number | int    |
+-----------------+----------+
order_number is the primary key (column with unique values) for this table.
This table contains information about the order ID and the customer ID.

 

Write a solution 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 result format is in the following example.

 

Example 1:

Input: 
Orders table:
+--------------+-----------------+
| order_number | customer_number |
+--------------+-----------------+
| 1      | 1         |
| 2      | 2         |
| 3      | 3         |
| 4      | 3         |
+--------------+-----------------+
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.

 

Follow up: What if more than one customer has the largest number of orders, can you find all the customer_number in this case?

Solutions

Solution 1: Group By + Sorting

We can use GROUP BY to group the data by customer_number, and then sort the groups in descending order by count(1). Finally, we can take the customer_number of the first record as the result.

# Write your MySQL query statement below
SELECT
  customer_number
FROM orders
GROUP BY customer_number
ORDER BY COUNT(1) DESC
LIMIT 1;

Solution 2

/* Write your T-SQL query statement below */
SELECT TOP 1
  customer_number
FROM
  orders
GROUP BY customer_number
ORDER BY COUNT(customer_number) DESC;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文