with tmp as ( select d.product_id, sum((price * cnt)) total_price, sum(cnt * in_price) sum_in_price from tb_order_detail d inner join tb_product_info info on d.product_id = info.product_id inner join tb_order_overall overall on overall.order_id = d.order_id where info.shop_id = 901 and date_format(event_time, '%Y-%m') >= '2021-10' and status = 1 group by d.product_id ) select '店铺汇总' as product_id, concat(round((1.0 - (sum(sum_in_price)/ sum(total_price) ))* 100,1),'%') 'profit_rate' from tmp union select product_id, concat(round((1.0 - (sum_in_price/ total_price ))* 100,1),'%') 'profit_rate' from tmp where (1.0 - (sum_in_price/ total_price ))* 100 > 24.9 group by product_id
先把 901 店 2021-10 以来每个商品的销售额和进价汇总到 tmp,再 union 出“店铺汇总”行和各商品>24.9% 的行。