- 两个方案
- 第一:先计算店铺整体毛利率,再计算各商品毛利率,通过union结合。这个可以结合其他结果看下
- 第二:with rollup可以计算 group by的总计数据,因此可以通过这个函数得到店铺的值。这样得到的product_id是null,所以需要在 having的时候加上 or product_id is null.然后通过coalesce 或者 ifnull函数把null修改为“店铺汇总”。整体如下:
select
coalesce(a.product_id,'店铺汇总') product_id,
concat(round((1-sum(in_price*cnt)/sum(price*cnt))*100,1),'%') profit_rate
from tb_product_info a join tb_order_overall b join tb_order_detail c
on a.product_id = c.product_id and b.order_id = c.order_id
where a.shop_id = '901' and date_format(b.event_time,'%Y%m') >= '202110'
group by a.product_id
with rollup
having 1-sum(in_price*cnt)/sum(price*cnt) > 0.249 or product_id is null
order by a.product_id