假设我有两个表,一个存储帐户,一个存储事务:
id acct_name opening_bal
1 checking 1029.99
2 savings 2002.19
...
还有
id date amount from_acct to_acct
...
99 2018-01-21 12.15 1 2
100 2018-01-21 9.99 4 1
101 2018-01-23 10.01 5 2
...
例如,交易表中的第99行表示12.15已于2018年1月21日从支票转为储蓄。
我想编写一个查询,该查询返回给定日期(例如今天或2018年10月12日等)上的所有帐户及其余额,诸如此类:
acct balance
checking 1599.21
savings 2221.99
...
我将如何编写这样的查询?
编辑:这是一个解决方案,与我想要的解决方案足够接近(它仅具有一个附加的id列)。您可以将CURDATE()替换为任意日期,以获取该日期的相应余额表。
SELECT id, acct_name, opening_bal+amt-amt2 as balance FROM accounts
INNER JOIN
(SELECT to_acct, sum(amount) AS amt
FROM transactions
WHERE date <= CURDATE()
GROUP BY to_acct) as T2
ON accounts.id=T2.to_acct
INNER JOIN
(SELECT from_acct, sum(amount) AS amt2
FROM transactions
WHERE date <= CURDATE()
GROUP BY from_acct) as T3
ON T2.to_acct = T3.from_acct
;
答案 0 :(得分:1)
类似这样的事情。如果您提供了更多数据,答案可能会更准确。 Table1是您的第一个表,Table2是第二个表。
select acct_name as acct,
opening_bal - t1.put_money + t2.get_money as balance
from Table1
left join (select from_acct, ifnull(sum(amount),0) as put_money from Table2 group by from_acct) t1
on t1.from_acct = Table1.id
left join (select to_acct, ifnull(sum(amount),0) as get_money from Table2 group by to_acct) t2
on t2.to_acct = Table1.id;