自己写的太繁琐了
用了union
1.联结3个表
from tb_order_detail a
join tb_order_overall b on a.order_id = b.order_id
join tb_product_info c on a.product_id =c.product_id
2.限制时间和店铺
-- 时间:大于等于2021年10月
-- 店铺:901
3.计算商品毛利率
(1-d.进货价格/avg(d.商品单价)
4.计算店铺毛利率(我一开始忘记×商品数量了)
(1-sum(e.进货价格*e.商品数量)/sum(e.商品单价*e.商品数量)
这里容易出错
-- 2021年10月以来店铺901中商品毛利率大于24.9%的商品信息及店铺整体毛利率。
-- 时间:大于等于2021年10月
-- 店铺:901
-- 商品毛利率(1-进价/平均单件售价):大于24.9%
-- 店铺整体毛利率(1-总进价成本/总销售收入)
select '店铺汇总' 商品ID,concat(round((1-sum(e.进货价格*e.商品数量)/sum(e.商品单价*e.商品数量))*100,1),'%') 商品毛利率
from
(select a.order_id 订单号,a.product_id 商品ID,a.price 商品单价,a.cnt 商品数量,
b.event_time 下单时间,b.total_amount 订单总金额,
c.shop_id 店铺ID,c.in_price 进货价格,c.release_time 上架时间
from tb_order_detail a
join tb_order_overall b on a.order_id = b.order_id
join tb_product_info c on a.product_id =c.product_id)e
where date_format(e.下单时间,'%Y-%m')>='2021-10' and e.店铺ID='901'
union
select f.商品ID,f.商品毛利率
from(select d.商品ID,concat(round((1-d.进货价格/avg(d.商品单价))*100,1),'%') 商品毛利率,d.进货价格,d.商品单价
from
(select a.order_id 订单号,a.product_id 商品ID,a.price 商品单价,
b.event_time 下单时间,b.total_amount 订单总金额,
c.shop_id 店铺ID,c.in_price 进货价格,c.release_time 上架时间
from tb_order_detail a
join tb_order_overall b on a.order_id = b.order_id
join tb_product_info c on a.product_id =c.product_id)d
where date_format(d.下单时间,'%Y-%m')>='2021-10' and d.店铺ID='901'
group by d.商品ID
having (1-d.进货价格/d.商品单价)>=0.249)f