[英]MYSQL: How to return query calculation result from three tables?
I have three tables: 我有三个表:
Table1: Salary
Fields: ID,Account_Num,Amount
Table2: Other_Income
Fields: ID,Account_Num,Amount
Table3: Expenses
Fields: ID,Account_Num,Amount
From the above tables,how to write a query which return a result, list all account from these table, and shows the balance of every account in these tables. 从上面的表格中,如何编写查询以返回结果,列出这些表格中的所有帐户,并显示这些表格中每个帐户的余额。
Result should show Account_num,Salary,Other_Income,Expenses, balance
( balance=Salary.amount+Other_Income.amount-expenses.amount
) 结果应显示
Account_num,Salary,Other_Income,Expenses, balance
( balance=Salary.amount+Other_Income.amount-expenses.amount
)
These three table may contains some different account number. 这三个表可能包含一些不同的帐号。
I have been thinking of this so long, tried union and join but still cant make it. 我一直在想这个很久了,尝试过加入并加入,但仍然做不到。
Somebody show/guide me? 有人向我展示/引导我吗?
I've had some luck with the following query. 我对以下查询有好运。 Essentially, I combine all the transactions in the Salary, Other_Income and Expenses tables into a single temp table named combined, and then use group by to sum all the transactions!
本质上,我将Salary,Other_Income和Expenses表中的所有交易合并到一个名为Combine的临时表中,然后使用group by汇总所有交易!
select Account_Num, sum(Amount)
from (
select Account_Num, Amount from Salary union
select Account_Num, Amount from Other_Income union
select Account_Num, -Amount from Expenses
) as Combined
group by Account_Num;
Following query might help , provided that every account has salary against it. 如果每个帐户都有薪水,以下查询可能会有所帮助。
select Account_Num,(total-d.Amount) as final_amount ( select Account_Num, ifnull(a.Amount,0)+ifnull(b.Amount,0) as total from Salary a
left join Other_Income b on a.Account_Num=b.Account_Num ) c
join Expenses d on c.Account_Num=d.Account_Num
SELECT Sal.`Account_Num`, sal.`Amount` AS Salary, ot_in.`Amount` AS ExtraIncome , exp.`Amount` AS expenses, (sal.`Amount`+ot_in.`Amount`-exp.`Amount`) As Balance FROM Salary AS Sal INNER JOIN Other_income AS ot_in ON Sal.`Account_Num` = ot_in.`Acount_num` INNER JOIN Expenses AS exp ON Sal.`Account_Num` = ex.`Account_Num`
在这里,您要从这三个表中获得通用帐号并从每个表中提取对应的金额,然后将表中的三个表连接起来,并使用给定的公式从收入中减去支出来计算剩余余额。我希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.