SQL语句练习四
题目描述
在表 orders 中找到订单数最多客户对应的 customer_number 。数据保证订单数最多的顾客恰好只有一位。表 orders 定义如下:
| Column | Type |
|-------------------|-----------|
| order_number (PK) | int |
| customer_number | int |
| order_date | date |
| required_date | date |
| shipped_date | date |
| status | char(15) |
| comment | char(200) |
样例输入
| 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 。
解题思路
此题考查两个知识点,一个是group,一个是limit。使用group针对customer_number做分组统计出订单数最多的用户。limit直接返回第一个,即为数量最多的用户。
解题答案
// limit可以写为limit 1;
select customer_number from orders group by customer_number order by count(customer_number) desc limit 0,1;
进阶:如果存在多个用户订单数一样多,如何返回对应所有的customer_number.
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
);
评论