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

20 富有的客户数量 #25

Open
astak16 opened this issue Jan 13, 2022 · 0 comments
Open

20 富有的客户数量 #25

astak16 opened this issue Jan 13, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Jan 13, 2022

题目

查询至少有一个订单金额大于 500 的客户数量。

create table store (
	bill_id int,
	customer_id int,
	amount int
);

insert into store values
(6, 1, 549),
(8, 1, 834),
(4, 2, 394),
(11, 3, 657),
(13, 3, 257);

SQL:方法一

select count(distinct customer_id) as rich_count from store where amount > 500;

解析

  • 先筛选出金额大于 500 的数据
  • customer_id 去重计数

SQL:方法二

select count(*) as rich_count from (
	select distinct customer_id from store
	group by customer_id having max(amount) > 500
) as temp;

解析

  • customer_id 分组,并筛选出 amount 大于 500 的客户,作为临时表 temp
  • temp 计数

SQL:方法三

with temp as (
	select distinct customer_id from store
	group by customer_id having max(amount) > 500
) select count(*) as rich_count from temp

解析

方法二的另一种写法,使用 with 创建临时表

SQL:方法四

select count(*) as rich_count from (
	select
		distinct customer_id,
		max(amount) over(partition by customer_id) as `max`
	from store
) as temp where `max` > 500;

解析

  • 使用窗口函数筛选出每个用户最大的金额,作为临时表 temp
  • 查询 temp 筛选出大于 500 的进行计数
@astak16 astak16 added the 简单 label Jan 13, 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