看了高赞答案才知道用ifnull搭配with rollup来对聚合函数的结果进行再求和,并重命名表头。自己再总结一下思路:
①各表连接,进行时间、店铺的筛选;
②根据p_id进行分组,计算毛利率,同时用ifnull搭配with rollup来对聚合函数的结果进行再求和,并重命名表头;

select ifnull(product_id,'店铺汇总') as product_id, concat(round((1-sum(cnt*in_price)/sum(cnt*price))*100,1),'%') as a
from(
SELECT product_id, price, cnt, in_price
        FROM tb_order_detail
        left JOIN tb_product_info USING(product_id)
        left JOIN tb_order_overall USING(order_id)
        WHERE shop_id = 901 and DATE(event_time) >= "2021-10-01"
) as tb1
group by product_id
with rollup
having a>24.9 or product_id is null
order by product_id