题目描述

我们有一个表:

  • order_info:包含订单信息,包括订单ID id、用户ID user_id、产品名称 product_name、订单状态 status、客户端ID client_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;