获取内部联接中两行的总和 table

Getting sum of two rows in an inner joined table

我有这两张表;

  1. 行程
id date revenue
1 01/01/2020 5000
2 01/01/2020 3000
3 02/01/2020 4000
4 02/01/2020 2000
  1. 开支
id tripid amount
1 1 500
2 1 300
3 2 400
4 2 200
5 2 700

我想获得一天内收取的收入总和和一天内的支出总和。我有以下 sql 结果,但总和完全错误。

SELECT i.id, sum(i.revenue) as total, i.date trip , sum(c.amount) as exp, c.tripid expenses FROM trip i INNER JOIN expenses c ON i.id = c.tripid GROUP BY i.date ORDER BY trip DESC

您可以按行程预聚合费用,然后在外部查询中再次聚合:

select t.date, sum(t.revenue) as revenue, coalesce(sum(e.expense), 0) as expense
from trips t
left join (
    select tripid, sum(amount) as expense
    from expenses
    group by tripid
) e on e.tripid = t.id
group by t.date