[牛客面试题 SQL16 零食类商品中复购率top3高的商品]

牛客面试题 SQL16 零食类商品中复购率top3高的商品

  • 问题:请统计零食类商品中复购率top3高的商品。
  • 定义:某商品 复购率=近90天购买它至少两次的人数/购买它的总人数。
    (近90天指包含最大日期(记为当天)在内的近90天)
    在这里插入图片描述
  • 近90天 购买它两次的人数。
	  select t.product_id,uid,count(*) as 用户购买的次数
			from tb_product_info t join tb_order_overall t1 join tb_order_detail t2 on t.product_id = t2.product_id and t1.order_id = t2.order_id
			where date(event_time) > date_sub((select date(max(event_time)) from tb_order_overall)
							,interval 89 day ) and tag='零食'  
			group by t.product_id,uid

在这里插入图片描述

-难点在于 按照 product_id 和 uid 分组之后,用count(*) 就能得到 用户购买的次数(就是当product_id 和uid 都出现的次数)

  • 个人认为 top 3应该用 dense_rank()
  • 注意,在开窗函数里使用排序函数之后,在外面就不能用order by 了。
  • 序号 函数
    row_number():显示分区中不重复不间断的序号(1,2,3,4
    dense_rank():显示分区中重复不间断的序号(1,2,2,3)
    rank():显示分区中重复间断的序号。(1,2,2,4
select product_id ,requrchase_rate
  from (
	  select  product_id,
	-- 		sum(if( 用户购买的次数>1,1,0)) 购买了2次的用户数,
	--         count(distinct uid) 购买的总人数,
			round(sum(if(用户购买的次数>1,1,0))/count(distinct uid),3)  requrchase_rate,
			rank() over(order by round(sum(if(用户购买的次数>1,1,0))/count(distinct uid),3)) 排名
	  from(
		  select t.product_id,uid ,count(*)
			from tb_product_info t join tb_order_overall t1 join tb_order_detail t2 on t.product_id = t2.product_id and t1.order_id = t2.order_id
			where date(event_time) > date_sub((select date(max(event_time)) from tb_order_overall)
							,interval 89 day ) and tag='零食'  
			group by t.product_id,uid
		) t
	group by product_id

) tt 
where 排名<=3
order by requrchase_rate desc,product_id ;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值