mysql - 连接多个表时数据量翻倍
问题描述
以 excel 格式链接到我所有的数据库表: 数据库
这是我的任务: 查找每个客户的总存款、总取款和总差额。
我所做的是
select c.customerid, customername, sum(d.depositamount) as 'Total Deposit', sum(w.withdrawalamount) as 'Total Withdraw', sum(d.depositamount) - sum(w.withdrawalamount) as 'differences'
from customers c left outer join deposits d on c.customerid = d.customerid
left outer join withdrawals w on c.CustomerID = w.CustomerID
group by c.CustomerID
order by c.CustomerID;
我的问题是“总存款”和“总提款”的数据翻了一番。由于这两列数据加倍,差值也加倍。我知道我可以将所有列除以 2 来解决问题,但我想知道这样做的正确方法。
我的问题是如何以不加倍数据的方式连接多个表?
(例如,“James Carlton Brokeridge”假设分别有 450、380 和 70)。
解决方案
您得到的值不正确,因为每次客户进行多次存款或取款时,都会导致在连接两个表时复制另一个(取款/存款)表中的行。要解决此问题,请在子查询中求和:
select c.customerid,
c.customername,
d.totaldeposit as 'Total Deposit',
w.totalwithdrawal as 'Total Withdraw',
d.totaldeposit - w.totalwithdrawal as 'differences'
from customers c
left outer join (
select customerid, sum(depositamount) as totaldeposit
from deposits
group by customerid
) d on c.customerid = d.customerid
left outer join (
select customerid, sum(withdrawalamount) as totalwithdrawal
from withdrawals
group by customerid
) w on c.customerid = w.customerid
order by c.customerid
推荐阅读
- sql-server - 我如何在 microsoft sql server 中使用 distinct 函数
- reactjs - 将 JS 路由反应到具有过滤数据的相同组件
- c++ - 将 Qt 与 Visual Studio 代码一起使用 (Windows)
- php - Laravel 为 auth 和 guest 用户路由不同的控制器
- java - hibernate一对多映射中各种子表的插入顺序
- javascript - 使用 AXIOS 和 VueJs 用二维数组映射数据
- javascript - 如何在请求后保存变量的值,但在第一次加载时有不同的值?
- python - jinja2.exceptions.TemplateNotFound 为什么会不断弹出?
- javascript - 如何使用 JavaScript 替换文本的多个实例?
- javascript - 如何将具有像现在 + 1 天这样的日期计算的字符串解析为日期对象?