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

alt

题目分析

本题要求统计每位快递员在2024年7月的总收入。总收入的计算方式为:基本工资 + 7月配送提成 - 7月支出。
输出字段

  • courier_id(快递员ID)
  • courier_name(快递员姓名)
  • total_income(总收入)

输出顺序:按快递员ID升序(courier_id asc)。
涉及知识点

  • SQL 多表连接(JOIN)
  • 子查询与分组聚合(SUM、GROUP BY)
  • 条件筛选(WHERE + month())
  • 字段别名与排序(ORDER BY)
  • 算术运算

解答步骤

1. 统计每位快递员7月的配送提成

  • 通过 couriers_infodeliveries_info 连接,筛选7月的配送记录,按快递员分组,统计每人7月的配送提成总额。
select c.courier_id, c.courier_name, c.base_salary,
sum(d.delivery_fee) as delivery_fee
from couriers_info c
join deliveries_info d on c.courier_id = d.courier_id
where month(d.delivery_date) = 7
group by c.courier_id

2. 统计每位快递员7月的支出

  • 通过 couriers_infoexpenses_info 连接,筛选7月的支出记录,按快递员分组,统计每人7月的支出总额。
select c.courier_id, c.courier_name,
sum(e.expense_amount) as expense_amount
from couriers_info c
join expenses_info e on e.courier_id = c.courier_id
where month(e.expense_date) = 7
group by c.courier_id

3. 汇总计算总收入

  • 将上述两个子查询以快递员ID为键连接,计算总收入:
    base_salary + delivery_fee - expense_amount
select t1.courier_id, t1.courier_name,
t1.base_salary + t1.delivery_fee - t2.expense_amount as total_income
from ( -- 上述第1步子查询 ) t1
join ( -- 上述第2步子查询 ) t2 on t1.courier_id = t2.courier_id
order by courier_id asc

完整代码

select t1.courier_id, t1.courier_name,
t1.base_salary + t1.delivery_fee - t2.expense_amount as total_income
from (
    select c.courier_id, c.courier_name, c.base_salary,
    sum(d.delivery_fee) as delivery_fee
    from couriers_info c
    join deliveries_info d on c.courier_id = d.courier_id
    where month(d.delivery_date) = 7
    group by c.courier_id
) t1
join (
    select c.courier_id, c.courier_name,
    sum(e.expense_amount) as expense_amount
    from couriers_info c
    join expenses_info e on e.courier_id = c.courier_id
    where month(e.expense_date) = 7
    group by c.courier_id
) t2 on t1.courier_id = t2.courier_id
order by courier_id asc

近似题目练习推荐

最受欢迎的top3课程

  • 知识点:SQL连接、时间差计算、分组、聚合函数、排序、限制输出

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