也是看了高赞回答和下面的评论才做出来的,针对评论中所说的 在架商品数量的子查询做了一点修改。 总结一下思路:求两个数, 1是对应日期7天内的在售商品数,用select里嵌套子查询进行遍历筛选7天内的时间; 2是在架商品数,用select里嵌套子查询遍历筛选销售日期之前上架的商品,即event_time>=r_time。 步骤: ①三个表连接作为子查询; ②表tb_order_overall作为主查询,主查询的每一个event_time去遍历子查询中的event_time,只要两者之差小于7天就count商品数,即得到每个一下单日期7天内的出售商品种数; ③同样,表tb_order_overall作为主查询,主查询的每一个event_time去遍历子查询中的release_time,只要下单时间≥上架时间就count商品数,即得到每一个下单日期之前上架的商品总的种数,用where筛选901店铺; ④输出去重的event_time,筛选10.1-10.3的日期,计算,排序。 select dt, round(sale_product_num/total_num,3) as sale_rate, round((1-sale_product_num/total_num),3) as unsale_rate from( select distinct date(event_time) as dt, (select count(distinct product_id) from tb_order_detail join tb_order_overall using(order_id) join tb_product_info using(product_id) where shop_id=901 and datediff(tb2.event_time, event_time) between 0 and 6) as sale_product_num, (select count(distinct product_id) from tb_order_detail join tb_order_overall using(order_id) join tb_product_info using(product_id) where tb2.event_time>=release_time and shop_id=901) as total_num from tb_order_overall tb2) as tb3 where date(dt) between '2021-10-01' AND '2021-10-03' order by dt