题解 | #某店铺的各商品毛利率及店铺整体毛利率#
某店铺的各商品毛利率及店铺整体毛利率
http://www.nowcoder.com/practice/65de67f666414c0e8f9a34c08d4a8ba6
新的函数用法:concat(profit_rate,%)可以在原来的基础上加上%,因此profit_rate需要100; with rollup 函数用在group by后面;可以对group by后面的第一个字段的内容开始分组求和,可以利用这个获得整个店铺的利润率,但product_id不是数字,rollup之后会返回null因此需要用到ifnull函数对null进行转换 ifnull(a,b)如果内容不是null返回第一个参数a,是null返回第二个参数b 解题思路:首先因为需要利用concat函数对profit_rate加上%,故需要用到第一个子查询找到profit_rate; 其次需要用聚合函数算出profit_rate,需要用到第二个子查询;(可以直接pricecnt,不需要用sum先算出来) 最后用having对单品利润进行筛选,同时记得product_id is null(店铺总利润)也需要放进来。
- SELECT product_id, CONCAT(profit_rate, "%") as profit_rate
- FROM (
-
SELECT IFNULL(product_id, '店铺汇总') as product_id,
-
ROUND(100 * (1 - SUM(in_price*cnt) / SUM(price*cnt)), 1) as profit_rate
-
FROM (
-
SELECT product_id, price, cnt, in_price
-
FROM tb_order_detail
-
JOIN tb_product_info USING(product_id)
-
JOIN tb_order_overall USING(order_id)
-
WHERE shop_id = 901 and DATE(event_time) >= "2021-10-01"
-
) as t_product_in_each_order
-
GROUP BY product_id
-
WITH ROLLUP
-
HAVING profit_rate > 24.9 OR product_id IS NULL
-
ORDER BY product_id
- ) as t1;