题解 | #某店铺的各商品毛利率及店铺整体毛利率#

某店铺的各商品毛利率及店铺整体毛利率

https://www.nowcoder.com/practice/65de67f666414c0e8f9a34c08d4a8ba6

#第一步:先把满足2021年10以来以及店铺为901的商品id,以及计算毛利率需要用到的数据导出来,这样可以让后续的代码看的更清楚简约些
with t as(
    select t1.product_id, in_price, price, cnt
    from tb_order_detail t3
    inner join tb_product_info t1
        on t1.product_id=t3.product_id
    inner join tb_order_overall t2
        on t2.order_id=t3.order_id
    where date(event_time) >= '2021-10-01'
    and shop_id= 901)

# 第二步:获取整个店铺的毛利率=(1-总进价成本/总销售收入)*100%
select  '店铺汇总' as product_id,
            concat( round(100* (1-sum(in_price*cnt)/sum(price*cnt)),1),'%') as profit_rate
from t
union
#因为这道题目里不存在重复数据的问题,所以union和union all都一样
# 第二步:连接毛利率大于24.9%的商品及其毛利率
# 因为in_price不依赖group by,不符合mysql里only_full_group_by原则,所以加上个max(),没有其他的含义,就是为了符合这个原则
# 这里用了个子查询,因为需要筛选出利润率大于24.9%的product_id,concat上%后,就不能进行大小的比较了。所以先获取不带百分号的利润率,where语句筛选完条件后再通过concat把%加上
select product_id, concat(profit_rate,'%')
from (select product_id,
                    round(100*(1-max(in_price)/avg(price)),1) as profit_rate
                    from t
                    group by product_id) tt
where profit_rate >24.9
#题解#
全部评论

相关推荐

头像
04-17 09:29
已编辑
湖南农业大学 后端
睡姿决定发型丫:本硕末9也是0offer,简历挂了挺多,只有淘天 美团 中兴给了面试机会,淘天二面挂,美团一面kpi面,中兴一面感觉也大概率kpi(虽然国企,但一面0技术纯聊天有点离谱吧)
点赞 评论 收藏
分享
05-20 13:59
门头沟学院 Java
米黑子米黑子:你这个成绩不争取下保研?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务