题解 | #牛客的课程订单分析(七)#
牛客的课程订单分析(七)
http://www.nowcoder.com/practice/d6f4a37f966145da8900ba9edcc4c068
第一步:在原表上添加2列数据,source和cnt。用到case when函数和count()over()函数。
select user_id
,(case when oi.is_group_buy='yes' then 'GroupBuy' else c.name end) source
,count(product_name)over(partition by client_id ) cnt
from order_info oi left join client c on oi.client_id=c.id
where oi.date>='2025-10-16'
and status='completed'
and oi.product_name in('C++','Java','Python')
,(case when oi.is_group_buy='yes' then 'GroupBuy' else c.name end) source
,count(product_name)over(partition by client_id ) cnt
from order_info oi left join client c on oi.client_id=c.id
where oi.date>='2025-10-16'
and status='completed'
and oi.product_name in('C++','Java','Python')
示例结果
557336|GroupBuy|2
557336|GroupBuy|2
57|PC|1
57|IOS|1
557336|GroupBuy|2
557336|GroupBuy|2
57|PC|1
57|IOS|1
到这一步看起来差不多了,只要group by 一下就能得到结果,但是还没满足同一个用户下单2个以及2个以上这个条件,所以要对id进行筛选。
第二步:找出同一个用户下单2个以及2个以上状态为购买成功的C++课程或Java课程或Python课程的ID。
select user_id from
(select user_id,count(product_name) cnt from order_info
where date>='2025-10-16'
and status='completed'
and product_name in('C++','Java','Python')
group by user_id
having cnt>=2) b
(select user_id,count(product_name) cnt from order_info
where date>='2025-10-16'
and status='completed'
and product_name in('C++','Java','Python')
group by user_id
having cnt>=2) b
示例结果
57
557336
557336
第三步,结合一、二步得到结果
select source,cnt from
(
select user_id
,(case when oi.is_group_buy='yes' then 'GroupBuy' else c.name end) source
,count(product_name)over(partition by client_id ) cnt
from order_info oi left join client c on oi.client_id=c.id
where oi.date>='2025-10-16'
and status='completed'
and oi.product_name in('C++','Java','Python')
) a where a.user_id in
(select user_id from
(select user_id,count(product_name) cnt from order_info
where date>='2025-10-16'
and status='completed'
and product_name in('C++','Java','Python')
group by user_id
having cnt>=2)b)
group by source,cnt
order by source
(
select user_id
,(case when oi.is_group_buy='yes' then 'GroupBuy' else c.name end) source
,count(product_name)over(partition by client_id ) cnt
from order_info oi left join client c on oi.client_id=c.id
where oi.date>='2025-10-16'
and status='completed'
and oi.product_name in('C++','Java','Python')
) a where a.user_id in
(select user_id from
(select user_id,count(product_name) cnt from order_info
where date>='2025-10-16'
and status='completed'
and product_name in('C++','Java','Python')
group by user_id
having cnt>=2)b)
group by source,cnt
order by source
示例结果
GroupBuy|2
IOS|1
PC|1
IOS|1
PC|1
查看7道真题和解析

vivo公司福利 364人发布