此题共包含三张表:
- 表1:tb_order_detail
- 表2:tb_order_overall
- 表3:tb_product_info
要解决的问题:
- 请统计零食类商品中复购率top3高的商品。
- 某商品复购率 = 近90天内购买它至少两次的人数 ÷ 购买它的总人数
- 近90天指包含最大日期(记为当天)在内的近90天。
- 结果中复购率保留3位小数,并按复购率倒序、商品ID升序排序
注:
用户将购物车中多件商品一起下单时,订单总表会生成一个订单,status-订单状态
- 订单状态为0表示待付款
- 订单状态为1表示已付款;
- 订单状态为2表示已退款
解题思路:
- 为了方便获取数据,连接三张表,并计算每个product_id和UID为分组的购买次数
- 筛选条件为近90天,tag为零食,以及status为1
- 以上表为基础计算,复购率=近90天内购买它至少两次的人数 ÷ 购买它的总人数
- 结果中复购率保留3位小数,并按复购率倒序、商品ID升序排序
知识点:
- sum(if...)可以用来统计条件语句的个数,count(*)可以用来统计总个数
- 叠加group by 可以大大提高代码的效率
SELECT product_id,
round(sum(if(buy_times>=2, 1, 0))/count(*),3) repurchase_rate
from(
SELECT tpi.product_id, uid, count(*) buy_times
from tb_order_detail tod
join tb_product_info tpi
on tod.product_id = tpi.product_id
join tb_order_overall too
on too.order_id = tod.order_id
where tag = '零食'
and DATEDIFF((SELECT max(event_time) max_time from tb_order_overall),event_time) <=89
and status =1
GROUP BY tpi.product_id, uid
) t1
GROUP BY product_id
ORDER BY repurchase_rate desc, product_id
limit 3