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

题目分析

本题要求统计不同商品类别(product_category)和不同年龄段(age_group)用户的总销售额(total_sales_amount),并计算每个类别在各年龄段的销售额占该年龄段总销售额的比例(purchase_percentage)。
输出字段包括:商品类别(升序排列)、年龄段、总销售额(保留两位小数)、购买占比(保留两位小数)。
输出顺序:按商品类别升序排列。
涉及知识点

  • SQL 多表连接(JOIN)
  • 分组聚合(GROUP BY + SUM)
  • 窗口函数(OVER + PARTITION BY)
  • 四则运算与保留小数(ROUND)
  • 字段别名与排序(ORDER BY)

解答步骤

  1. 多表连接

    • sales 表记录了每笔销售,products 表提供商品类别,customer_info 表提供用户年龄段。
    • 通过 JOIN 语句将三表关联:
      • sales.product_id = products.product_id
      • sales.sale_id = customer_info.sale_id
  2. 分组与聚合

    • 以商品类别(p.category)和年龄段(c.age_group)为分组依据,统计每组的总销售额:
      • sum(s.quantity * s.price) 计算每组的销售总额
      • ROUND(..., 2) 保留两位小数
  3. 窗口函数计算占比

    • sum(s.quantity * s.price) over (partition by c.age_group) 计算每个年龄段的总销售额
    • 用分组销售额除以该年龄段总销售额,得到购买占比
    • ROUND(..., 2) 保留两位小数
  4. 排序与输出

    • 最终结果按商品类别升序排列(order by p.category asc

完整代码

select 
    p.category as product_category,
    c.age_group, 
    round(sum(s.quantity * s.price), 2) as total_sales_amount,
    round(sum(s.quantity * s.price) / sum(s.quantity * s.price) over (partition by c.age_group), 2) as purchase_percentage
from sales s
join products p on p.product_id = s.product_id
join customer_info c on c.sale_id = s.sale_id 
group by p.category, c.age_group
order by p.category asc

近似题目练习推荐

用户订单查询

  • 知识点:窗口函数、分组聚合、SQL多表连接

获取指定客户每月的消费额

  • 知识点:SQL连接、聚合函数、分组、日期函数

统计所有课程参加培训人次

  • 知识点:字符串处理、聚合函数、分组

如需更多类似题目,可在牛客网SQL练习区搜索“窗口函数”、“分组聚合”等关键词进行练习。