零食类top3商品
题目描述:
商品信息表tb_product_info
| id | product_id | shop_id | tag | int_ | quantity | release_time |
| 1 | 8001 | 901 | 零食 | 60 | 1000 | 2020-01-01 10:00:00 |
| 2 | 8002 | 901 | 零食 | 140 | 500 | 2020-01-01 10:00:00 |
| 3 | 8003 | 901 | 零食 | 160 | 500 | 2020-01-01 10:00:00 |
订单总表tb_order_overall
| id | order_id | uid | event_time | total_amount | total_cnt | status |
| 1 | 301001 | 101 | 2021-09-30 10:00:00 | 140 | 1 | 1 |
| 2 | 301002 | 102 | 2021-10-01 11:00:00 | 235 | 2 | 1 |
| 3 | 301011 | 102 | 2021-10-31 11:00:00 | 250 | 2 | 1 |
| 4 | 301003 | 101 | 2021-10-02 10:00:00 | 300 | 2 | 1 |
| 5 | 301013 | 105 | 2021-10-02 10:00:00 | 300 | 2 | 1 |
| 6 | 301005 | 104 | 2021-10-03 10:00:00 | 170 | 1 | 1 |
| id | order_id | product_id | price | cnt |
| 1 | 301001 | 8002 | 150 | 1 |
| 2 | 301011 | 8003 | 200 | 1 |
| 3 | 301011 | 8001 | 80 | 1 |
| 4 | 301002 | 8001 | 85 | 1 |
| 5 | 301002 | 8003 | 180 | 1 |
| 6 | 301003 | 8002 | 140 | 1 |
| 7 | 301003 | 8003 | 180 | 1 |
| 8 | 301013 | 8002 | 140 | 2 |
| 9 | 301005 | 8003 | 180 | 1 |
-
用户将购物车中多件商品一起下单时,订单总表会生成一个订单(但此时未付款, status-订单状态-订单状态为0表示待付款),在订单明细表生成该订单中每个商品的信息;
-
当用户支付完成时,在订单总表修改对应订单记录的status-订单状态-订单状态为1表示已付款;
-
若用户退货退款,在订单总表生成一条交易总金额为负值的记录(表示退款金额,订单号为退款单号,订单状态为2表示已退款)。
| product_id | repurchase_rate |
| 8001 | 1.000 |
| 8002 | 0.500 |
| 8003 | 0.333 |
select product_id,round(sum(case when ranking>1 then 1 else 0 end)/count(DISTINCT uid),3) rate from
(select product_id,uid,ROW_NUMBER() over(partition by product_id,uid order by event_time) ranking
from tb_order_detail left join tb_product_info using (product_id) left JOIN tb_order_overall using (order_id)
where tag='零食' and status=1
and datediff((select max(event_time) from tb_order_overall),event_time)<90
#and timestampdiff(day,event_time,(select max(event_time) from tb_order_overall)) between 0 and 89
#and datediff((select max(date(event_time)) from tb_order_overall),date(event_time)) <90
)t
group by product_id
order by rate desc,product_id asc
limit 3
巧妙之处在于不用计数,按照用户和商品分组,排名超过2 的均表示购买了超过两次,并且可以方便计算出任意购买次数的比例,只需令ranking=n即可!
所以数量筛选问题新思路:转化为窗口函数排序问题

浙公网安备 33010602011771号