题解 | #牛客的课程订单分析(五)#
牛客的课程订单分析(五)
http://www.nowcoder.com/practice/348afda488554ceb922efd2f3effc427
思路: 1.首先,将满足基本条件的用户及购买日期次序,购买次数取出,作为子表
select *
,ROW_NUMBER() over(partition by user_id order by date ) as date_num
,count(*) over(partition by user_id) as cnt
from order_info
where date > '2025-10-15'
and status = 'completed'
and product_name in ('C++','Python ','Java')
2.得到总表后,需要进行行列转换,常用的方式就是聚合函数,行列转换必须只有一个值对应,这个时候可以用到min聚合函数进行提取 最后的结果如下
select a.user_id
,min(case when a.date_num = 1 then a.date end) as first_buy_date
,min(case when a.date_num = 2 then a.date end) as second_buy_date
,a.cnt
from
(
select *
,ROW_NUMBER() over(partition by user_id order by date ) as date_num
,count(*) over(partition by user_id) as cnt
from order_info
where date > '2025-10-15'
and status = 'completed'
and product_name in ('C++','Python ','Java')
)a
where a.cnt >1
group by a.user_id
order by a.user_id