This below query gives name,id,subscribed,opening,closing,totalAmount details of a particular year i.e posted_date is the input to the query.
select la.name,la.id,la.parent_id,la.is_group,tb1.opening op_1,tb1.closing cl_1,
coalesce((select sum(j.amount) from journal j,voucher v , ledger_account le where j.voucher_id=v.id and le.id=j.ledger_account_id and la.id=le.id and
v.posted_date::date>='2020-04-01' and v.posted_date::date<='2021-03-31'),0) balance_2020
from ledger_account la left join trialb tb1 on tb1.ledger_account_id=la.id and tb1.fy_id=1
The above query gives total data and balance of year 2020, For Ex:- If i need the balances from year 2005, I again need to paste the below logic multiple times
coalesce((select sum(j.amount) from journal j,voucher v , ledger_account le where j.voucher_id=v.id and le.id=j.ledger_account_id and la.id=le.id and v.posted_date::date>='2020-04-01' and v.posted_date::date<='2021-03-31'),0) balance_2020
and change the v.posted date and column name as
v.posted_date::date>='2005-04-01' and v.posted_date::date<='2006-03-31'),0) balance_2005 and so on for almost 15 times to get total balances until year 2020 by which size of query keeps increasing every year and time taken process.
So is there any alternate or possible way using which the columns balance_2005,balance_2006.. so on can be generated dynamically if necessary based on the input given to the query?
DATE.'2020-04-01'is just a string that must be converted to date, which can fail. UseDATE '2020-04-01'instead.