# 条件:课程范围为('C++','Python','Java'),日期条件为2025-10-15之后,状态为 completed # 1、先用窗口函数,用户分组,排序购买日期,以及计数购买次数。注意,这里排序只能用 rank(),因为值相等时不会重复,不会产生空位,row_number()因为值相等时会重复,会产生空位,就导致后续计算取排名1和2的记录时,有可能没有2的记录,dense_rank() 值相等时会重复 # 2、根据1计算结果,设定好条件,购买次数>=2,用户id分组,用case when和聚合函数,取第一次和第二次购买日期,以及购买次数 with t as ( select user_id ,product_name ,date ,rank() over(partition by user_id order by date) as buy_date_rank ,count(id) over(partition by user_id) as cnt from order_info where product_name in ('C++','Python','Java') and status='completed' and date>'2025-10-15' ) select user_id ,max(case when buy_date_rank=1 then date end) as first_buy_date ,max(case when buy_date_rank=2 then date end) as second_buy_date ,max(cnt) as cnt from t where cnt>=2 group by user_id order by user_id