题解 | #店铺901国庆期间的7日动销率和滞销率#
#这个题最终我才用的最瓜皮的做法,我写的另两种方法问题都比较多,就不放出来了,而且复杂。
step1: e 表用来拆选出合适的数据,就是找出9月25日---10月3日的901店铺的详细产品记录
d表用来吧这三个瓜皮日期union在一起(记录中,特别是这种记录分组重叠,这道题用一把梭子的方式不好写,而这个瓜皮的写法正好可以)
step2: 将 d left e ,在on条件中匹配d表中的time相应的符合条件的范围,
step3: group by d.time 过滤出这三天在自己范围内的销售量,
step4: join tb_product_info g 表 就是为了找到这个用户在相应范围发布的商品的数量。
后面又left tb_order_overall表的event_time ,目的是应为条件中说,“只要当天任一店铺有任何商品的销量就输出该天的结果,即使店铺901当天的动销率为0。”,(当天的动销率为0,任意店铺没有销量,不输出。当天的动销率为0,任意店铺有销量,要输出),说实话很恶心。
step5:group by就可以了,统计输出, having 条件写上,having 后面跟的条件就是过滤出step4后半段描述的内容
#店铺901 #2021 年 国庆头三天,每天的七日动销率和滞销率,保留3位小数,按日期升序排序 select f.time as dt, format(max(f.saleNum)/count(distinct g.id),3) as sale_rate, format((count(distinct g.id) - max(f.saleNum))/count(distinct g.id),3) as unsale_rate from ( select d.time,count(distinct e.product_id) as saleNum from ( select '2021-10-01' as time union select '2021-10-02' as time union select '2021-10-03' as time )d left join ( select a.product_id,date_format(c.event_time,'%Y-%m-%d') as time from (select * from tb_product_info where date_format(release_time,'%Y-%m-%d') <= '2021-10-03' and shop_id='901') a join tb_order_detail b on a.product_id=b.product_id join tb_order_overall c on b.order_id = c.order_id and date_format(c.event_time,'%Y-%m-%d') <= '2021-10-03' and date_format(c.event_time,'%Y-%m-%d') >= date_sub('2021-10-01', interval 6 day) ) e on e.time <= d.time and e.time >= date_sub(d.time, interval 6 day) group by d.time ) f join tb_product_info g on f.time >= date_format(g.release_time,'%Y-%m-%d') and g.shop_id='901' left join (select date_format(event_time,'%Y-%m-%d') as time from tb_order_overall) h on h.time = f.time group by f.time having count(h.time)>0
###2023/6/20 想到的新的解决方法,小地方的改变,把判断是否需要输出的逻辑放到了【group by dt having count(if(event_date=dt,1,null)) > 0】,没有上个解决方法好 select dt,format(sale_type_num/all_sale_type,3) as sale_rate,format((all_sale_type-sale_type_num)/all_sale_type,3) as unsale_rate from ( select dt,max(sale_type_num) as sale_type_num,count(distinct product_id) as all_sale_type from tb_product_info a join ( select dt,count(distinct product_id) as sale_type_num from ( select '2021-10-03' as dt union select '2021-10-02' as dt union select '2021-10-01' as dt ) t5 left join ( select product_id,date_format(event_time,'%Y-%m-%d') as event_date from ( select t1.product_id,t2.order_id from ( select product_id from tb_product_info where shop_id=901 and release_time <= '2021-10-03' ) t1 join tb_order_detail t2 on t1.product_id=t2.product_id ) t3 right join tb_order_overall t4 on t3.order_id = t4.order_id and date_format(event_time,'%Y-%m-%d') <= '2021-10-03' ) t6 on t6.event_date <= t5.dt and t6.event_date >= date_sub(t5.dt,interval 6 day) group by dt having count(if(event_date=dt,1,null)) > 0 ) b on date_format(a.release_time,'%Y-%m-%d') <= b.dt and shop_id=901 group by dt ) c order by dt