繁体   English   中英

两个表中两列的总和-MySQL

[英]Sum of two columns from two tables - MySQL

我有三张桌子

t1
CustId    Name
1         XYZ
2         PQR

t2
CustId    Income
1         100
1         200
2         50
2         100

t3
CustId   Expense
1        50
1        70
2        30
2        40

我需要运行查询以获取以下结果

CustId    Total Income     Total Expense
1         300              120
2         150              70

我已经尝试了正常的SUM和Group By,但是结果与预期的却大不相同...

我尝试的查询是

SELECT t1.custid, SUM(t2.Income), SUM(t3.Expense) FROM t1
LEFT JOIN t2 ON t1.custId = t2.CustId
LEFT JOIN t3 ON t1.CustId = t3.CustId
GROUP BY t1.CustId

任何帮助,您将不胜感激。

尝试对所有三个表进行内部联接,然后按客户ID将结果分组,例如:

SELECT t1.custId, SUM(t2.Income), SUM(t3.expense)
FROM t1 INNER JOIN t2
ON t1.custId = t2.custId
INNER JOIN t3
ON t2.custId = t3.custId
GROUP BY t1.custId

请尝试以下查询。

SELECT t1.CustID, IFNULL(tbl1.Income,0) AS 'TotalIncome', IFNULL(tbl2.Expenses,0) AS 'TotalExpenses' 
FROM t1
LEFT JOIN (SELECT t2.CustID,SUM(Income) AS 'Income' FROM t2 GROUP BY t2.CustID) tbl1
ON t1.CustID = tbl1.CustID
LEFT JOIN (SELECT t3.CustID,SUM(Expenses) AS 'Expenses' FROM t3 GROUP BY t3.CustID) tbl2
ON t1.CustID = tbl2.CustID;

SQL小提琴: http ://sqlfiddle.com/#!9 / ad05d / 8

您可以使用以下查询来实现您想要的

SELECT t1.custid, ti.Income, te.expense FROM t1 LEFT JOIN (select t2.custId, sum(t2.Income) as income from t2 group by t2.custId) as ti ON t1.custId = ti.CustId LEFT JOIN (select t3.custId, sum(t3.Expense) as expense from t3 group by t3.custId) as te ON t1.CustId = te.CustId

至于为什么您以前的查询不起作用。 我可以给出以下解释。

在SQL中,无论何时进行连接,数据库都会在内部生成所有条目的笛卡尔积,并取决于返回数据的where子句。 所以当你做了

SELECT t1.custid, SUM(t2.Income), SUM(t3.Expense) FROM t1 LEFT JOIN t2 ON t1.custId = t2.CustId

您有4行,在这些行中重复有customerId,现在当您通过在customerId上应用相等条件与t3表联接时,数据库将能够在两条记录中匹配customerID,因此您将获得8行。 这就是为什么您的查询无法正常工作的原因

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM