I'm having difficulty writing an SQL query that will correctly group account_no together and subtracting an amount.
Firstly I wrote this query which updates everything fine except ACCOUNT_NO A-102 should end up as 4500 not as two different correct balances.
select transactions.account_no, account.balance, transactions.amount,
(account.balance + transactions.amount) AS "CORRECT BALANCE"
from transactions, account
where account.account_no = transactions.account_no;
ACCOUNT_NO| BALANCE | AMOUNT | CORRECTBALANCE
A-102 | 4000 | 2000 | 6000
A-102 | 4000 | -1500 | 2500
A-222 | 8000 | -1000 | 7000
A-305 | 2000 | 1300 | 3300
I tried to sum and group by the account_no but I cannot work out how to do this with the two tables. This was just something I tried but could not get to work.
select transactions.account_no, SUM(transactions.amount)
from transactions
group by transactions.account_no;
ACCOUNT_NO| SUM(TRANSACTIONS.AMOUNT)
A-305 | 1300
A-102 | 500
A-222 | -1000
The expected outcome should be:
ACCOUNT_NO| BALANCE | AMOUNT | CORRECTBALANCE
A-102 | 4000 | 500 | 4500
A-222 | 8000 | -1000 | 7000
A-305 | 2000 | 1300 | 3300
This is because the account A-102 it has two different amounts coming out, but from the same balance.