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

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

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

首先,利用表连接,将店铺商品信息与用户的订单购买信息结合起来,合并成宽表,提取出我们所需要计算的成本总额,收入总额等,找出所需要的信息作为临时表:

1.找出901号店铺的产品信息,作为左表

2.使用left join 连接产品与订单表中相关的金额与单量数据,就过滤掉了其他店铺的货物信息

with c as 
(
    select product_id
        ,sum(price*cnt) as sum_sold
        ,sum(in_price*cnt) as sum_in
    from
        (
        select a.product_id
              ,a.in_price
              ,a.quantity
              ,t.order_id
              ,t.price
              ,t.cnt
              ,o.total_amount
              ,o.total_cnt
        from
        (select* from tb_product_info where shop_id='901')a #注意限定店铺号
        left join tb_order_detail t 
        on a.product_id = t.product_id
        left join tb_order_overall o on t.order_id = o.order_id
        where date_format(event_time,'%Y-%m') >='2021-10' and o.status = 1
        )b
    group by product_id
    )

接着,将需要计算的所有参数进行计算

1.注意保留小数使用round

2.最终表现用%链接,所以需要计算得数*100后,使用concat与其拼接

select '店铺汇总'as product_id
      ,concat(round((1-sum(sum_in)/sum(sum_sold))*100,1),'%') as profit_rate
from c
    union
select product_id
      ,concat(round((1-sum_in/sum_sold)*100,1),'%') as profit_rate
from c  
where round((1-sum_in/sum_sold)*100,1) > 24.9

最后的脚本表示为:

with c as 
(
    select product_id
        ,sum(price*cnt) as sum_sold
        ,sum(in_price*cnt) as sum_in
    from
        (
        select a.product_id
              ,a.in_price
              ,a.quantity
              ,t.order_id
              ,t.price
              ,t.cnt
              ,o.total_amount
              ,o.total_cnt
        from
        (select* from tb_product_info where shop_id='901')a #注意限定店铺号
        left join tb_order_detail t 
        on a.product_id = t.product_id
        left join tb_order_overall o on t.order_id = o.order_id
        where date_format(event_time,'%Y-%m') >='2021-10' and o.status = 1
        )b
    group by product_id
    )
    select '店铺汇总'as product_id
      ,concat(round((1-sum(sum_in)/sum(sum_sold))*100,1),'%') as profit_rate
from c
    union
select product_id
      ,concat(round((1-sum_in/sum_sold)*100,1),'%') as profit_rate
from c  
where round((1-sum_in/sum_sold)*100,1) > 24.9
数据库刷题题解 文章被收录于专栏

数据分析数据库题目练习题解

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 11:30
仁者伍敌:kpi都懒得刷了属于是
点赞 评论 收藏
分享
05-25 10:45
门头沟学院 Java
Frank_zhan...:没实习一个项目肯定不够,可以再做一个轮子,技术栈再补一个mq,微服务,整体再换个简历模板,暑期尽量再找一个日常实习
无实习如何秋招上岸
点赞 评论 收藏
分享
见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 16:15
我应届生,去年10月份开始在这家公司实习,到今年10月份正好一年想(实习+试用期),在想要不要提前9月份就离职,这样好找工作些,但又差一个月满一年,又怕10月份国庆回来离职,容易错过了下半年的金九银十,到年底容易gap到年后
小破站_程序员YT:说这家公司不好吧,你干了快一年 说这家公司好吧,你刚毕业就想跑路说你不懂行情吧,你怕错过金九银十说 你懂行情吧,校招阶段在实习,毕业社招想换工作 哥们,我该怎么劝你留下来呢
应届生,你找到工作了吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务