SELECT t.* ,ah.* from accounts_heads as ah left join ( SELECT ledger_id,SUM(op_debit_total) as op_debit_total,SUM(op_credit_total) as op_credit_total, SUM(debit_total) as debit_total,SUM(credit_total) as credit_total from ( SELECT ledger_id,SUM(amount) as op_debit_total,0 op_credit_total,0 debit_total,0 credit_total FROM `journal_transactions` WHERE status=1 and type=0 and date < '2022-03-01' and ledger_id is not null and ledger_id > 0 GROUP by ledger_id UNION SELECT ledger_id,0 op_debit_total,SUM(amount) as op_credit_total,0 debit_total,0 credit_total FROM `journal_transactions` WHERE status=1 and type=1 and date < '2022-03-01' and ledger_id is not null and ledger_id > 0 GROUP by ledger_id UNION SELECT ledger_id,0 op_debit_total,0 op_credit_total,SUM(amount) as debit_total,0 credit_total FROM `journal_transactions` WHERE status=1 and type=0 and date >= '2022-03-01' and date <= '2022-03-09' and ledger_id is not null and ledger_id > 0 GROUP by ledger_id UNION SELECT ledger_id,0 op_debit_total,0 op_credit_total,0 debit_total,SUM(amount) as credit_total FROM `journal_transactions` WHERE status=1 and type=1 and date >= '2022-03-01' and date <= '2022-03-09' and ledger_id is not null and ledger_id > 0 GROUP by ledger_id ) as t group by ledger_id ) as t on ah.id=t.ledger_id