Customer table
id | name | customerid
1 | Philip James | ac1001
2 | Frank Mathew | ac1002
Credit table
id| year | customer | amount
1 | 2020 | ac1001 | 1000
2 | 2020 | ac1001 | 1000
3 | 2020 | ac1001 | 1000
4 | 2020 | ac1001 | 1000
5 | 2019 | ac1001 | 1000
6 | 2019 | ac1001 | 2000
7 | 2020 | ac1002 | 2000
8 | 2020 | ac1002 | 2000
Debit table
id| year | customer| amount
1 | 2020 | ac1001 | 1000
2 | 2020 | ac1001 | 1000
3 | 2020 | ac1001 | 1000
4 | 2020 | ac1001 | 1000
5 | 2019 | ac1001 | 2000
6 | 2019 | ac1001 | 2000
7 | 2020 | ac1002 | 2000
8 | 2020 | ac1002 | 2000
I am trying to get the balance for each customer dynamically in respect to the year, i tried using this;
SELECT debit.year,customers.name,customers.customerid,SUM(debit.amount),SUM(credit.amount),
SUM(COALESCE((debit.amount),0)-COALESCE((credit.amount),0))AS balance FROM
customers
RIGHT JOIN credit ON customers.customerid=credit.customer
RIGHT JOIN debit ON customers.customerid=debit.customer GROUP BY customers.customerid,debit.year
Query Result
year| customer | sum(debit)| sum(credit)| Balance
2020 | ac1001 | 48000 | 42000 | 6000
2020 | ac1002 | 8000 | 6000 | 2000
But what i need is this table below, thank you
Expected Result
year| customer | sum(debit)| sum(credit)| Balance
2019 | ac1001 | 4000 | 3000 | 1000
2020 | ac1001 | 4000 | 4000 | 0
2020 | ac1002 | 4000 | 4000 | 0