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

题目分析

本题要求找出2024年销量最高的商品,输出该商品的ID、名称、总销售额和总销量。
输出字段

  • product_id(商品ID)
  • product_name(商品名称)
  • total_sales_amount(总销售额)
  • total_sales_quantity(总销量)

输出顺序:按商品ID升序(order by product_id)。
涉及知识点

  • SQL 多表连接(JOIN)
  • 子查询与分组聚合(SUM、GROUP BY)
  • 窗口函数(RANK() OVER ORDER BY)
  • 条件筛选(WHERE + 时间区间)
  • 字段别名与排序(ORDER BY)

解答步骤

1. 统计2024年每个商品的总销售额和总销量

  • sales_records 销售记录表中,筛选2024年内的销售数据,按商品ID分组,统计每个商品的总销售额和总销量。
select product_id, sum(sales_amount) as total_sales_amount, sum(sales_quantity) as total_sales_quantity 
from sales_records
where sales_date between '2024-01-01' and '2024-12-31'
group by product_id

2. 按总销量降序排名

  • 用窗口函数 rank() over(order by total_sales_quantity desc),按总销量降序给每个商品排名。
select *,
rank() over(order by total_sales_quantity desc) as rk
from ( -- 上述子查询 ) sub

3. 关联商品信息并筛选销量最高的商品

  • 将上述结果与 products 商品表通过商品ID连接,获取商品名称。
  • 只保留排名第1的商品(销量最高)。
from products p
join ( -- 上述子查询 ) s on s.product_id = p.product_id
where rk = 1

4. 排序输出

  • 按商品ID升序排序。
order by product_id

完整代码

select s.product_id, p.product_name, s.total_sales_amount, s.total_sales_quantity
from products p
join (
    select *,
    rank() over(order by total_sales_quantity desc) as rk
    from (
        select product_id, sum(sales_amount) as total_sales_amount, sum(sales_quantity) as total_sales_quantity 
        from sales_records
        where sales_date between '2024-01-01' and '2024-12-31'
        group by product_id
    ) sub
) s on s.product_id = p.product_id
where rk = 1
order by product_id

近似题目练习推荐

获得积分最多的人(二)

  • 知识点:窗口函数、分组排名、条件筛选

查询出不同类别商品中,销售金额排名前三且利润率超过 20%的商品信息

  • 知识点:窗口函数、条件筛选

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