获取内部连接表中两行的总和
Posted
技术标签:
【中文标题】获取内部连接表中两行的总和【英文标题】:Getting sum of two rows in an inner joined table 【发布时间】:2021-03-29 18:39:47 【问题描述】:我有这两张表;
-
旅行
id | date | revenue |
---|---|---|
1 | 01/01/2020 | 5000 |
2 | 01/01/2020 | 3000 |
3 | 02/01/2020 | 4000 |
4 | 02/01/2020 | 2000 |
-
费用
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
【问题讨论】:
见meta.***.com/questions/333952/… 【参考方案1】:您可以按行程预先聚合费用,然后在外部查询中再次聚合:
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
【讨论】:
以上是关于获取内部连接表中两行的总和的主要内容,如果未能解决你的问题,请参考以下文章
mysql 如何查找同一表中两行之间的差异并列出不匹配的记录? mysql在表中查找不匹配的行