select * from (select debits.glcode as 'glcode', debits.name as 'name',IF(debits.type = 'ASSET' or debits.type = 'EXPENSES', ifnull(debits.debitamount,0)-ifnull(credits.creditamount,0),'') as 'debit', IF(debits.type = 'INCOME' or debits.type = 'EQUITY' or debits.type = 'LIABILITIES', ifnull(credits.creditamount,0)-ifnull(debits.debitamount,0),'') as 'credit' from (select acc_coa.gl_code as 'glcode',name,sum(amount) as 'debitamount',acc_coa.type as 'type' from acc_journal_entry,acc_coa where acc_coa.id = acc_journal_entry.coa_id and acc_journal_entry.type='DEBIT' and acc_journal_entry.entry_date between '2012-11-01' and '2012-11-31' group by name order by glcode) debits LEFT OUTER JOIN (select acc_coa.gl_code,name,sum(amount) as 'creditamount',acc_coa.type as 'type' from acc_journal_entry,acc_coa where acc_coa.id = acc_journal_entry.coa_id and acc_journal_entry.type='CREDIT' and acc_journal_entry.entry_date between '2012-11-01' and '2012-11-31' group by name order by glcode) credits on debits.name=credits.name union select credits.glcode as 'glcode', credits.name as 'name',IF(credits.type = 'ASSET' or credits.type = 'EXPENSES', ifnull(debits.debitamount,0)-ifnull(credits.creditamount,0),'') as 'debit', IF(credits.type = 'INCOME' or credits.type = 'EQUITY' or credits.type = 'LIABILITIES', ifnull(credits.creditamount,0)-ifnull(debits.debitamount,0),'') as 'credit' from (select acc_coa.gl_code as 'glcode',name,sum(amount) as 'debitamount',acc_coa.type as 'type' from acc_journal_entry,acc_coa where acc_coa.id = acc_journal_entry.coa_id and acc_journal_entry.type='DEBIT' and acc_journal_entry.entry_date between '2012-11-01' and '2012-11-31' group by name order by glcode) debits RIGHT OUTER JOIN (select acc_coa.gl_code,name,sum(amount) as 'creditamount',acc_coa.type as 'type' from acc_journal_entry,acc_coa where acc_coa.id = acc_journal_entry.coa_id and acc_journal_entry.type='CREDIT' and acc_journal_entry.entry_date between '2012-11-01' and '2012-11-31' group by name order by glcode) credits on debits.name=credits.name) as fullouterjoinresult order by glcode