# 【要求】:根据上述表格,查询出每个快递员在 2024 年 7 月的总收入(基本工资 + 派送费用总和 - 支出 )。查询结果按照快递员 ID 升序排列。要求查询出来的表格的字段如下:
# courier_id: 快递员的唯一标识符。
# courier_name: 快递员的姓名。
# total_income: 快递员2024 年 7 月的总收入。

#本体需注意,join d表和e表时,若某配送员配送费2个,支出3个,那么join后,配送费仍是两个,但支出会膨胀成3*2个。
#所以sum两个表的两个字段时,先sum再join。
select c.courier_id as courier_id
,courier_name
,base_salary+sum_d-sum_e as total_income
from couriers_info c
left join (
    select courier_id,sum(delivery_fee) as sum_d
    from deliveries_info 
    where delivery_date like '2024-07%'
    group by courier_id
) as d on c.courier_id=d.courier_id
left join (
    select courier_id,sum(expense_amount) as sum_e
    from expenses_info
    where expense_date like '2024-07%'
    group by courier_id
) as e on c.courier_id=e.courier_id
order by courier_id;