表1:员工
EmpId CreatedAt
--------------------------
100 2015-11-09 07:21:02
200 2017-01-24 18:24:01
300 2016-08-20 06:55:35
表2:帐户
AccId EmpID Currency CreatedAt
-----------------------------------------------
9000 100 USD 2017-04-20 19:40:55
9001 200 USD 2017-04-20 19:40:55
9002 100 EUR 2017-05-20 19:40:55
9003 200 USD 2017-04-20 19:40:55
9004 100 USD 2017-04-20 19:40:55
表3:交易
TrnsId AccId Amount CreatedAt
------------------------------------------
10 9000 3000 2017-04-25 19:40:55
11 9001 500 2017-05-25 19:40:55
12 9000 -200 2017-05-30 19:40:55
13 9000 -500 2017-06-11 19:40:55
我需要在每次交易输入后计算该帐户的期末余额。假设每个帐户的余额都为零。
我写了这个查询:
SELECT
account.AccId, SUM(transaction.amount) AS [Ending Balance]
FROM
account
JOIN
transaction ON transaction.AccId = account.AccId
GROUP BY
account.AccId
但查询返回的结果不正确。