LeetCode刷题-数据库(MySQL)- 586.订单最多的客户

586.订单最多的客户

一、题目描述

在表 order 中找到订单数最多客户对应的 customer_number
数据能够保证订单数最多的客户恰好只有一位。

orders 定义如下:

Column Type
order_number (PK) int
customer_number int
order_date date
required_date date
shipped_date date

样例输入

order_number customer_number order_date required_date shipped_date status comment
1 1 2017-04-09 2017-04-13 2017-04-12 Closed
2 2 2017-04-15 2017-04-20 2017-04-18 Closed
3 3 2017-04-16 2017-04-25 2017-04-20 Closed
4 3 2017-04-18 2017-04-28 2017-04-25 Closed

样例输出

customer_number
3

解释
customer_number 为 ‘3’ 的顾客有两个订单,比顾客 ‘1’ 或者 ‘2’ 都要多,因为他们只有一个订单
所以结果是该顾客的 customer_number ,也就是 3 。

**进阶:**如果有多位顾客订单数并列最多,你能找到他们所有的 customer_number 吗?

二、思路分析

因为题目数据能够保证订单数最多的客户恰好只有一位,所以GROUP BY后以COUNT(*)降序排列取第一行数据即可。

进阶: 先算出最高的订单数是多少,然后只需要在之前的基础上找出与最高订单数相等的行即所求。

三、代码实现

SELECT
	customer_number
FROM
	orders
GROUP BY customer_number
ORDER BY COUNT(*) DESC
LIMIT 1

进阶:

SELECT
	customer_number
FROM
	orders o1
GROUP BY o1.customer_number
HAVING COUNT(*) = (
			SELECT
				COUNT(*)
			FROM
				orders o2
			GROUP BY o2. customer_number
			ORDER BY COUNT(*) DESC
			LIMIT 1
	);

你可能感兴趣的:(MySQL)