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
)
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!
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`
在这里,您要从这三个表中获得通用帐号并从每个表中提取对应的金额,然后将表中的三个表连接起来,并使用给定的公式从收入中减去支出来计算剩余余额。我希望这会有所帮助。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.