前言
练习sql语句,所有题目来自于力扣(https://leetcode.cn/problemset/database/)的免费数据库练习题。
今日题目:
586.订单最多的客户
表:Orders
列名 | 类型 |
---|---|
order_number | int |
customer_number | int |
查找下了最多订单的客户的 customer_number 。测试用例生成后,恰好有一个客户比任何其他客户下了更多的订单。
我那不值一提的想法:
首先分析表,题目给了一个订单表,记录了订单的编号,以及顾客的编号,现在需要找到最多订单的客户,我认为肯定要计算出现的次数,所以得先group by customer_number,然后记录次数,然后通过order by函数去排序,由于order by 默认排序是升序,所以还得加desc变成降序,最后使用limit 1取第一个数,得到下了最多订单的客户。
select customer_number
from Orders
group by customer_number
having count(customer_number)
order by count(customer_number) desc
limit 1
看了题解,我注意到了一个我做题的时候没有注意到的问题,因为题目中强调了恰好有一个客户比任何其他客户都下了更多订单,所以结果只有一个,那么如果有多么客户并列第一呢。这里就需要用到子查询,筛选条件count等于最大的customer_number。
select customer_number
from Orders
group by customer_number
having count(customer_number) =
(select count(customer_number)from Ordersgroup by customer_numberhaving count(customer_number)order by count(customer_number) desclimit 1
)
结果:
总结:
能运行就行。