1. 先计算近90天内购买它至少两次的人数

    1.1 先将三个表进行连接

    1.2 筛选出零食和从当天开始计算的近90天数据

    1.3 根据产品id和用户id分组聚合,筛选出购买次数至少两次的记录

    1.4 求出每个商品购买次数至少两次的个数

  2. 购买它的总人数

    2.1 根据产品id分组聚合,去重计数得到购买该产品的总人数

  3. 90天内购买它至少两次的人数/购买它的总人数--得到复购率

  4. 排序筛选出前三个记录

with t as (
  select tod.product_id,count(distinct uid) total_cnt
  from tb_order_overall too,tb_order_detail tod,tb_product_info tpi
  where too.order_id=tod.order_id
  and tod.product_id=tpi.product_id
  and tag='零食'
  and DATE_ADD(date(event_time),interval 89 day)>=( select max(date(event_time))
                                                    from tb_order_overall)
  group by tod.product_id
),-- 购买每个产品的总人数表
m as (
  select tod.product_id,uid,count(tod.order_id) cnt
  from tb_order_overall too,tb_order_detail tod,tb_product_info tpi
  where too.order_id=tod.order_id
  and tod.product_id=tpi.product_id
  and tag='零食'
  and DATE_ADD(date(event_time),interval 89 day)>=( select max(date(event_time))
                                                    from tb_order_overall)
  group by tod.product_id,uid  
  having cnt>=2
) -- 每个商品至少被购买次数两次的商品信息表
select t.product_id,round(count(cnt)/total_cnt,3) repurchase_rate
from t 
left join m  
on t.product_id=m.product_id
group by t.product_id
order by repurchase_rate desc,t.product_id
limit 3