题解 | #某店铺的各商品毛利率及店铺整体毛利率#
某店铺的各商品毛利率及店铺整体毛利率
http://www.nowcoder.com/practice/65de67f666414c0e8f9a34c08d4a8ba6
通过代码
with t as (SELECT
t_d.product_id,
sum(price * cnt) outprice,
sum(cnt) sums,
in_price
FROM
tb_order_detail t_d
JOIN(SELECT
product_id,
in_price
FROM
tb_product_info
WHERE
shop_id = 901) t_i
ON t_d.product_id = t_i.product_id
join(SELECT
order_id
FROM
tb_order_overall
WHERE
status = 1
and event_time > '2021-09-30 23:59:59') t_o
ON t_o.order_id = t_d.order_id
GROUP BY
product_id)
SELECT
'店铺汇总' product_id,
concat( round((1 - sum(sums * in_price) / sum(outprice)) * 100,1),'%') profit_rate
FROM
t
UNION ALL
select
product_id,
concat( round((1-(sums * in_price) / outprice) * 100,1),'%') profit_rate
FROM
t
WHERE
round((1-(sums * in_price) / outprice) * 100,1) > 24.9
思路
用户将购物车中多件商品一起下单时,订单总表会生成一个订单(但此时未付款,status-订单状态为0表示待付款),在订单明细表生成该订单中每个商品的信息;
当用户支付完成时,在订单总表修改对应订单记录的status-订单状态为1表示已付款;
若用户退货退款,在订单总表生成一条交易总金额为负值的记录(表示退款金额,订单号为退款单号,status-订单状态为2表示已退款)。
请计算2021年10月以来店铺901中商品毛利率**大于24.9%**的商品信息及店铺整体毛利率。
注:商品毛利率=(1-进价/平均单件售价)*100%;
店铺毛利率=(1-总进价成本/总销售收入)100%。
结果**先输出店铺毛利率,再按商品ID升序输出各商品毛利率**,均保留1位小数。
我们先列出来901商店里的商品id,以及进价
SELECT
product_id,
in_price
FROM
tb_product_info
WHERE
shop_id = 901
然后在订单总表里面找到订单状态为已付款
(在这里我本来想还要找订单状态为已退款,然后如果是表里的付款订单就抵消,然后发现好像并不需要)
以及订单产生时间大于2021-10
SELECT
order_id
FROM
tb_order_overall
WHERE
status = 1
and event_time > '2021-09-30 23:59:59'
然后综合上边两表以及题上的第三个表找到出售总金额这里有一点注意:
并不是每一单卖出同样商品的价格都一样!
SELECT
t_d.product_id,
sum(price * cnt) outprice,
sum(cnt) sums,
in_price
FROM
tb_order_detail t_d
JOIN(1) t_i
ON t_d.product_id = t_i.product_id
join(2) t_o
ON t_o.order_id = t_d.order_id
GROUP BY
product_id
这里体现汇总结果,我们用了union而不是COALESCE,因为COALESCE只能用在汇总是最后一行的的情况
一天一个Mysql 文章被收录于专栏
学习,一天一个mysql