最近做了oppo的24年春招题,题目如下: alt alt

题目分析

本题要求统计每个产品与竞争对手的销售对比分析,计算产品的年度总销售额以及与竞争对手的销售差额。
输出字段

  • product_id(产品ID)
  • product_name(产品名称)
  • competitor_name(竞争对手名称)
  • total_sales_amount_of_product(产品年度总销售额)
  • sales_difference_with_competitor(与竞争对手的销售差额)

输出顺序:题目未指定排序,默认按分组顺序输出。
涉及知识点

  • SQL 多表连接(JOIN)
  • 分组聚合(SUM、GROUP BY)
  • 字段别名
  • 算术运算

解答步骤

1. 关联产品、销售和竞争对手信息

  • oppo_products_detail 产品表与 sales_info 销售信息表通过产品ID连接,获取每个产品的季度销售数据。
  • 再与 competitor_analysis 竞争对手分析表通过产品ID连接,获取竞争对手信息。
from oppo_products_detail o
join sales_info s on s.product_id = o.product_id
join competitor_analysis c on c.product_id = o.product_id

2. 计算产品年度总销售额

  • 将四个季度的销售额相加:sum(s.quarter_1_sales_amount + s.quarter_2_sales_amount + s.quarter_3_sales_amount + s.quarter_4_sales_amount)
sum(s.quarter_1_sales_amount + s.quarter_2_sales_amount + s.quarter_3_sales_amount + s.quarter_4_sales_amount) as total_sales_amount_of_product

3. 计算与竞争对手的销售差额

  • 用产品年度总销售额减去竞争对手的2023年总销售额:sum(四个季度销售额) - c.total_competitor_sales_amount_2023
sum(s.quarter_1_sales_amount + s.quarter_2_sales_amount + s.quarter_3_sales_amount + s.quarter_4_sales_amount) - c.total_competitor_sales_amount_2023 as sales_difference_with_competitor

4. 分组输出

  • 按产品ID、竞争对手名称、竞争对手2023年总销售额分组。
group by o.product_id, c.competitor_name, c.total_competitor_sales_amount_2023

完整代码

select o.product_id, o.product_name, c.competitor_name,
sum(s.quarter_1_sales_amount + s.quarter_2_sales_amount + s.quarter_3_sales_amount + s.quarter_4_sales_amount) as total_sales_amount_of_product,
sum(s.quarter_1_sales_amount + s.quarter_2_sales_amount + s.quarter_3_sales_amount + s.quarter_4_sales_amount) - c.total_competitor_sales_amount_2023 as sales_difference_with_competitor
from oppo_products_detail o
join sales_info s on s.product_id = o.product_id
join competitor_analysis c on c.product_id = o.product_id
group by o.product_id, c.competitor_name, c.total_competitor_sales_amount_2023

近似题目练习推荐

了解 2023 年全年所有商品的盈利情况

  • 知识点:分组聚合、多表连接、算术运算

如需更多类似题目,可在牛客网SQL练习区进行练习。