题目描述
我们有一个表:
order_info
:包含订单信息,包括订单IDid
、用户IDuser_id
、产品名称product_name
、订单状态status
、客户端IDclient_id
和订单日期date
。
目标是查询出在2025年10月15日之后,同一个用户下单2个及以上状态为“completed”的“C++”、“Java”或“Python”课程订单的用户ID,并按用户ID升序排序。
知识点
- 条件过滤:使用
WHERE
子句筛选符合条件的记录。 - 聚合函数:使用
COUNT
函数计算每个用户的订单数量。 - 子查询:在
FROM
子句中使用子查询来计算每个用户的订单数量。 - 排序:使用
ORDER BY
子句按用户ID升序排列结果。
关键问题分析
1. 筛选符合条件的订单
我们需要筛选出状态为“completed”的订单,产品名称为“C++”、“Java”或“Python”,并且订单日期在2025年10月15日之后:
where status = 'completed' and product_name in ('C++','Java','Python') and date > '2025-10-15'
2. 计算每个用户的订单数量
我们使用COUNT
函数计算每个用户的订单数量,并使用GROUP BY
子句按用户ID分组:
select
user_id,
count(*) as cnt
...
group by user_id
3. 筛选订单数量大于等于2的用户
我们通过WHERE
子句筛选出订单数量大于等于2的用户:
where cnt >= 2
4. 排序输出
我们按用户ID升序排列输出结果:
order by user_id
完整代码
select user_id
from(
select
user_id,
count(*) as cnt
from order_info
where status = 'completed' and product_name in ('C++','Java','Python') and date > '2025-10-15'
group by user_id
) sub
where cnt >= 2
order by user_id;