请统计零食类商品中复购率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='零食')
通过上述代码得到如下结果,将零食类我们需要的信息得到
这一个表再来考虑明显比三个表连接直接操作考简单得多。
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
以上代码即可得到如下结果
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
总结:遇到这种多表连接类型的题目,直接开始求指标可能容易把问题想复杂。
为了逻辑更清晰,建议像我这样先将有用的信息都提炼出来成一个表再来操作。