算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从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;
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: