Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

42 订单最多的顾客 #51

Open
astak16 opened this issue Feb 14, 2022 · 0 comments
Open

42 订单最多的顾客 #51

astak16 opened this issue Feb 14, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Feb 14, 2022

题目

查询出最多订单的客户  customer_number 。

create table orders (order_number int, customer_number int);
insert into orders (order_number, customer_number) values
(3,5),
(5,1),
(6,5),
(7,4),
(8,6),
(9,2),
(10,4),
(11,16),
(12,3),
(13,5),
(14,3),
(15,16),
(16,3);

进阶:如果有多位顾客订单数并列最多,你能找到他们所有的  customer_number  吗?

分析

通过 分组倒序排序 将订单最多的客户放到最上面,在通过 limit 将第一条数据拿出来。

SQL:方法一

select
 customer_number
from orders group by customer_number
order by count(customer_number) desc limit 1;

解析

方法一只能查出一位订单数最多的客户

  1. 通过 group bycustomer_number 进行分组
  2. 使用 count 计算出每个顾客的订单数,按照倒序进行排序
  3. 因为是倒序排序,所以使用 limit 取第一条数据
    1. limit offset length 第一个数是偏移量,第二个数是要取的长度
    2. limit 1 表示从第一条数据开始取一条

SQL:方法二

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;

解析

方法二是进阶,查询出多位顾客订单数并列最多

  1. 使用 group bycustomer_number 进行分组
  2. 使用 count() 计算出每个顾客的订单数,倒序排列
  3. 使用窗口函数 dense_rank() 按照 每个顾客的订单数进行排名
  4. 将其作为临时表,查询这个临时表,筛选出排名第一的顾客
@astak16 astak16 added the 简单 label Feb 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant