qiayue
2023-04-01 10:29:33 +08:00
拆分问题,第一步找出所有购买两次以上的用户数量,第二步找出所有购买用户数量,用两个 sql 分别查一次,之后用程序算复购比例,这会比只用一个 sql 查询更快。
第一个 sql 找出所有购买了 2 次以上的用户数量,这里假设 status = 1 表示订单已支付:
select count(t.customer_id) buy_2_times_customer_c from (select customer_id,count(distinct order_id) order_c from order where paid_at>='2022.01.01' and paid_at<='2023.03.01' and status=1 group by customer_id having order_c>=2) t
第二个 sql 找出所有购买用户数量:
select count(distinct customer_id) total_customer_c from order where paid_at>='2022.01.01' and paid_at<='2023.03.01' and status=1
最后用 buy_2_times_customer_c / total_customer_c 就是比例了。