select product_id, round(sum(repurchase) / count(*),3) as repurchase_rate from ( select product_id,uid,if(count(*)>1,1,0) as repurchase from tb_order_detail a left join tb_order_overall b using (order_id) left join tb_product_info using(product_id) where tag = '零食' and date(event_time)>( select date_sub(max(date(event_time)),interval 90 day) from tb_order_overall ) group by product_id,b.uid order by product_id ) t1 group by product_id order by repurchase_rate desc,product_id limit 3
内结构,即找到最大日期前90天的数据后,就不会写了。
此时得到的是每个商品中每个购买者的记录数据,居然不会求复购率
做法:
先按商品和用户分组,只有组内数据大于1的说明才有复购行为,于是输出一列新列,将大于1的组别赋予1,代表这组存在复购行为。
之后再嵌套一个查询,以商品分类,此时count就是90天内购买这个商品的人数,而sum(前面的复购字段),则是这个商品中存在复购行为的人数。做除法就能得到复购率
最后忘了题目限制种类是零食,以及只输出前3列数据。
这题思路其实不难,只是没转过弯,写出内循环后想了很久.......