题解 | #零食类商品中复购率top3高的商品#

零食类商品中复购率top3高的商品

http://www.nowcoder.com/practice/9c175775e7ad4d9da41602d588c5caf3

请统计零食类商品中复购率top3高的商品。

1.题目中有三个表,很多人可能立马感觉很麻烦了,而实际上我们要求复购率,需要得只有 uid,event_time,product_id这三项得信息,因此我们考虑先用with t as 将他们提炼出来再进行计算。

with t as 
(select a.product_id,b.uid,b.event_time as dt
from tb_product_info as a join tb_order_detail as c on a.product_id=c.product_id
join tb_order_overall as b on c.order_id=b.order_id
where tag='零食')

通过上述代码得到如下结果,将零食类我们需要的信息得到

alt

这一个表再来考虑明显比三个表连接直接操作考简单得多。

2.我们需要判断在90天内用户购买商品的次数

select  product_id,uid,count(uid) cu
from t 
where dt>date_sub((select max(event_time) from tb_order_overall),interval
                  90 day)
group by product_id,uid

以上代码即可得到如下结果

alt

3.剩下的使用公式计算复购率即可。使用if或者case when都可。

select product_id,
round(sum(if(cu>=2,1,0))/count(uid),3) rr
from u 
group by product_id
order by rr desc,product_id
limit 3

其中u为2中的结果。

完整代码如下:

with t as 
(select a.product_id,b.uid,b.event_time as dt
from tb_product_info as a join tb_order_detail as c on a.product_id=c.product_id
join tb_order_overall as b on c.order_id=b.order_id
where tag='零食')


select product_id,
round(sum(if(cu>=2,1,0))/count(uid),3) rr
from
(select  product_id,uid,count(uid) cu
from t 
where dt>date_sub((select max(event_time) from tb_order_overall),interval
                  90 day)
group by product_id,uid) as u 
group by product_id
order by rr desc,product_id
limit 3 

总结:遇到这种多表连接类型的题目,直接开始求指标可能容易把问题想复杂。

为了逻辑更清晰,建议像我这样先将有用的信息都提炼出来成一个表再来操作。

全部评论
该牛油正在参与牛客写题解薅羊毛的活动,牛币,周边,京东卡超多奖品放送,活动进入倒计时!快来捡漏啦https://www.nowcoder.com/discuss/888949?source_id=profile_create_nctrack&channel=-1
点赞 回复 分享
发布于 2022-04-20 17:15

相关推荐

小鹏、大疆、米哈游、MinMax小鹏上午投的下午就约面,进度未免也太快了
蛇年行大运fff:哥们 盗贴有意思吗,我发xhs上的给你搬过来了😅😅😅
点赞 评论 收藏
分享
评论
18
7
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务