方法一:基于订单分析(二)

原创:https://blog.nowcoder.net/n/d31d9107fe2f4f68bdf3e9edac6f1954?f=comment

不同的地方是,这里的排序方式是通过 id 来进行排序,而且需要返回的字段是表中全部字段。

故此我们可以先通过订单分析二中的方法获取到购买数量大于等于2 user_id,再联立 order_info 表查出所有数据,但此时需要注意的是,还需要再进行一次如下判断:

and status = 'completed'
and date > '2025-10-15'
and product_name in ('C++', 'Java', 'Python')

因为在子查询中只查询出了user_id,这个用户并不是很"干净",可能还买了其他课程或者status='un_completed'等其他的杂数据,我们需要再次过滤一遍。最后使用 id 升序排序即可。

完整代码:

select *
from order_info
where user_id in (select user_id
                    from order_info
                    where status = 'completed'
                    and date > '2025-10-15'
                    and product_name in ('C++', 'Java', 'Python')
                    group by user_id
                    having count(user_id) > 1)
and status = 'completed'
and date > '2025-10-15'
and product_name in ('C++', 'Java', 'Python')
order by id

方法二:使用窗口函数

原创:https://blog.nowcoder.net/n/721b2887f2ac4328829dcc826e4abbb0?f=comment

根据题目可知,使用到的表格只有一个,同一个用户下单2个以及2个以上状态为购买成功的C++课程或Java课程或Python课程的订单信息可知,需要在group by进行count,果断选择窗口函数

select id,user_id,product_name,`status`,client_id,`date`
from(
select id,user_id,product_name,`status`,client_id,`date`,
       count(*)over(partition by user_id ) as c1
from order_info
where `date`>='2025-10-15'
and `status`='completed'
and product_name in('C++','Python','Java'))c
where  c.c1>=2
order by id