# Write your MySQL query statement below
586. 订单最多的客户
表: Orders
+-----------------+----------+ | Column Name | Type | +-----------------+----------+ | order_number | int | | customer_number | int | +-----------------+----------+ Order_number是该表的主键。 此表包含关于订单ID和客户ID的信息。
编写一个SQL查询,为下了 最多订单 的客户查找 customer_number
。
测试用例生成后, 恰好有一个客户 比任何其他客户下了更多的订单。
查询结果格式如下所示。
示例 1:
输入: Orders 表: +--------------+-----------------+ | order_number | customer_number | +--------------+-----------------+ | 1 | 1 | | 2 | 2 | | 3 | 3 | | 4 | 3 | +--------------+-----------------+ 输出: +-----------------+ | customer_number | +-----------------+ | 3 | +-----------------+ 解释: customer_number 为 '3' 的顾客有两个订单,比顾客 '1' 或者 '2' 都要多,因为他们只有一个订单。 所以结果是该顾客的 customer_number ,也就是 3 。
进阶: 如果有多位顾客订单数并列最多,你能找到他们所有的 customer_number
吗?
原站题解
pythondata 解法, 执行用时: 260 ms, 内存消耗: 60.2 MB, 提交时间: 2023-08-09 17:30:59
import pandas as pd def largest_orders(orders: pd.DataFrame) -> pd.DataFrame: order_counts = orders['customer_number'].value_counts() # 统计每个顾客号的订单数量 max_orders = order_counts.max() # 获取最大订单数量 largest_customers = order_counts[order_counts == max_orders] # 筛选出订单数量等于最大值的顾客号 return largest_customers.reset_index().rename(columns={'index': 'customer_number'})[['customer_number']]
pythondata 解法, 执行用时: 288 ms, 内存消耗: 59.7 MB, 提交时间: 2023-08-09 17:30:37
import pandas as pd def largest_orders(orders: pd.DataFrame) -> pd.DataFrame: if orders.empty: return pd.DataFrame({'customer_number': []}) result = orders['customer_number'].value_counts().idxmax() return pd.DataFrame({'customer_number': [result]})
mysql 解法, 执行用时: 839 ms, 内存消耗: 0 B, 提交时间: 2022-06-06 10:22:44
select customer_number from Orders group by customer_number order by count(order_number) desc limit 1;