最近做了京东的24年春招题,题目如下:
题目分析
本题要求统计2024年1月至2024年6月期间,每个商品的总销售额。
输出字段:
- product_id(商品ID)
- product_name(商品名称)
- total_sales(总销售额)
输出顺序:按商品ID升序(order by product_id)。
涉及知识点:
- SQL 多表连接(JOIN)
- 条件筛选(WHERE + 时间区间)
- 分组聚合(SUM、GROUP BY)
- 字段别名与排序(ORDER BY)
解答步骤
1. 关联商品与销售表
- 用
products_underline
商品表与sales_underline
销售表通过商品ID(product_id)连接,获取每个商品的销售记录。
from products_underline p
join sales_underline s on p.product_id = s.product_id
2. 筛选2024年1月至6月的销售数据
- 只保留销售月份在2024年1月至6月之间的销售记录。
where s.sale_month between '2024-01' and '2024-06'
3. 统计每个商品的总销售额
- 按商品ID分组,统计每个商品的总销售额(单价 * 数量)。
sum(p.price * s.quantity) as total_sales
group by product_id
4. 排序输出
- 按商品ID升序排序。
order by product_id
完整代码
select p.product_id, p.product_name,
sum(p.price * s.quantity) as total_sales
from products_underline p
join sales_underline s on p.product_id = s.product_id
where s.sale_month between '2024-01' and '2024-06'
group by product_id
order by product_id
近似题目练习推荐
- 知识点:SQL连接、聚合函数、分组、日期函数
查询出每个品牌在不同月份的总销售额以及购买该品牌商品的用户的平均年龄
- 知识点:SQL多表连接、条件筛选、分组聚合
如需更多类似题目,可在牛客网SQL练习区进行练习。