题解 | #第一次购买成功课程的日期,以及购买成功课程的次数#
牛客的课程订单分析(四)
http://www.nowcoder.com/practice/c93d2079282f4943a3771ca6fd081c23
方法1,在上一题的基础上给子表加字段即可:
with t_user as ( select o.user_id, count(1) ct from order_info o where o.date > '2025-10-15' and o.status = 'completed' and o.product_name in ('C++', 'Java', 'Python') group by o.user_id having count(1) >= 2 ) select a.user_id, min(a.date) first_buy_date, b.ct cnt from order_info a, t_user b where a.user_id = b.user_id and a.date > '2025-10-15' and a.status = 'completed' and a.product_name in ('C++', 'Java', 'Python') group by a.user_id order by user_id;
方法2,直接通过group by来分组取最小日期和次数,注意having用法:
select a.user_id, min(a.date) first_buy_date, count(1) cnt from order_info a where a.date > '2025-10-15' and a.status = 'completed' and a.product_name in ('C++', 'Java', 'Python') group by a.user_id having count(1) >= 2 order by user_id;