题解 | #某店铺的各商品毛利率及店铺整体毛利率#
某店铺的各商品毛利率及店铺整体毛利率
https://www.nowcoder.com/practice/65de67f666414c0e8f9a34c08d4a8ba6
select ifnull (product_id, '店铺汇总'),#请注意这个地方可以设置别名,但是在group by 中不可以用别名,原因是这个属性只是针对原有的product_id进行一个 concat ( round( (1 - (sum(in_price * cnt) / sum(price * cnt))) * 100, 1 ), '%' ) allinprice from tb_product_info join tb_order_detail using (product_id) join tb_order_overall using (order_id) where date(event_time) >= '2021-10-01' AND shop_id = '901' group by product_id# 此点与上文对应,不可以用别名来做分组 with rollup having (1 - (sum(in_price * cnt) / sum(price * cnt))) >0.249 #因为同一个商店的同一个商品卖的价格会不一样,所以需要按照进价总量与售价总量来计算 or product_id is null order by product_id
本题难度很大,第一了解题目需要按照商品总的进价和总的售价来计算商品的利润,第二个知识点是如果要在本题进行一个rollup汇总列的替换,就不能用别名,因为一旦用了别名那么汇总列就会根据别名来,就不会进入ifnull的函数判断了。第三个知识点是一个执行的顺序因为select 是在having之后,所以我们筛选的时候要把汇总行也要算入,所以需要判断product_id is null。具体代码如上