列表

详情


2082. 富有客户的数量

表: Store

+-------------+------+
| Column Name | Type |
+-------------+------+
| bill_id     | int  |
| customer_id | int  |
| amount      | int  |
+-------------+------+
在 SQL 中,bill_id 是这个表的主键。
每一行包含一个订单的金额及相关客户的信息。

 

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

返回结果格式如下示例所示:

 

示例:

输入:
Store 表:
+---------+-------------+--------+
| bill_id | customer_id | amount |
+---------+-------------+--------+
| 6       | 1           | 549    |
| 8       | 1           | 834    |
| 4       | 2           | 394    |
| 11      | 3           | 657    |
| 13      | 3           | 257    |
+---------+-------------+--------+
输出: 
+------------+
| rich_count |
+------------+
| 2          |
+------------+
解释:
客户 1 有 2 个订单金额严格大于 500。
客户 2 没有任何订单金额严格大于 500。
客户 3 有 1 个订单金额严格大于 500。

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
# Write your MySQL query statement below

pythondata 解法, 执行用时: 276 ms, 内存消耗: 58.7 MB, 提交时间: 2023-08-09 15:03:38

import pandas as pd

def count_rich_customers(store: pd.DataFrame) -> pd.DataFrame:
    rich_count = store[store['amount'] > 500]['customer_id'].nunique()
    result = pd.DataFrame({'rich_count': [rich_count]})
    return result

mysql 解法, 执行用时: 450 ms, 内存消耗: 0 B, 提交时间: 2023-07-31 10:43:47

# Write your MySQL query statement below
# 使用窗口函数筛选出每个用户最大的金额,作为临时表 temp
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;

mysql 解法, 执行用时: 338 ms, 内存消耗: 0 B, 提交时间: 2023-07-31 10:43:09

# Write your MySQL query statement below
# 0x02 with xx as 建临时表
with temp as (
	select distinct customer_id from store
	group by customer_id having max(amount) > 500
) select count(*) as rich_count from temp

mysql 解法, 执行用时: 573 ms, 内存消耗: 0 B, 提交时间: 2023-07-31 10:42:36

# Write your MySQL query statement below
# 0x02 按 customer_id 分组筛选出 amount 大于 500 的客户
select count(*) as rich_count from (
	select distinct customer_id from store
	group by customer_id having max(amount) > 500
) as temp;

mysql 解法, 执行用时: 288 ms, 内存消耗: 0 B, 提交时间: 2023-07-31 10:41:22

# Write your MySQL query statement below
select count(distinct(customer_id)) as rich_count from Store where amount > 500;

上一题