首页 文章详情

​LeetCode刷题实战586:订单最多的客户

程序IT圈 | 119 2022-04-26 07:31 0 0 0
UniSMS (合一短信)
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 订单最多的客户,我们先来看题面:
https://leetcode-cn.com/problems/customer-placing-the-largest-number-of-orders

Write an SQL query 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.


解题

思路:

S1:使用 group by 对 customer_number 进行分组;
S2:使用 count() 计算出每个顾客的订单数,倒序排列;
S3:使用窗口函数 dense_rank() 按照 每个顾客的订单数进行排名;
S4:将其作为临时表,查询这个临时表,筛选出排名第一的顾客。

select customer_number from (
  select
    customer_number,
    dense_rank() over(order by count(*) desc) as rn
  from orders group by customer_number
) temp where rn = 1;


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-580题汇总,希望对你有点帮助!
LeetCode刷题实战581:最短无序连续子数组
LeetCode刷题实战582:杀掉进程
LeetCode刷题实战583:两个字符串的删除操作
LeetCode刷题实战584:寻找用户推荐人
LeetCode刷题实战585:2016年的投资

good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter