题解 | #某店铺的各商品毛利率及店铺整体毛利率#
某店铺的各商品毛利率及店铺整体毛利率
https://www.nowcoder.com/practice/65de67f666414c0e8f9a34c08d4a8ba6
with a as (select * from tb_product_info where shop_id = 901), b as (select * from tb_order_overall where status =1 and event_time > '2021-10-01'),tmp as (select a.product_id,a.in_price,c.price,c.cnt, a.in_price*c.cnt as totalin, c.price*c.cnt as totalout from a join tb_order_detail c on a.product_id=c.product_id join b on c.order_id = b.order_id ) select * from (select '店铺汇总' as product_id, concat(round((1-sum(totalin)/sum(totalout))*100,1),'%') profit_rate from tmp union select product_id, concat(round((1-sum(totalin)/sum(totalout))*100,1),'%') profit_rate from tmp group by product_id having left(profit_rate,4) > 24.9) p
我还是太全面了 这也能写出来........
- 先建3张临时表(a/b/tmp) 表c是detail原表 表a用来锁定店铺901 表b锁定已支付订单且下单日期在10月开始
- 表tmp将3张表连接 得到每个product_id所对应的进货价in_price、售价price、订购数cnt,进货价*数量=总原价totalin,售价*数量=总售价totalout
- 对于各商品的毛利率 需要groupby分组 having限定毛利率>24.9 -->得到各个商品的product_id和毛利率profit_rate
- 对于店铺汇总表 无需分组 -->得到汇总的id"店铺汇总"和毛利率profit_rate
- 使用union联结
需要注意的是:如果某个商品的毛利率<= 24.9 那么他不会在union表中出现 但是店铺汇总还是需要计算它的