SELECT * from ( SELECT 'V' as Ind, subq.Voucher_ID, subq.Voucher_Prefix, subq.Voucher_Type, (select ledger_name from $master_db.ledger_master where ledger_id = Against_Ledger) as Ledger,  subq.Voucher_Date as 'Voucher Date', subq.Voucher_ID as 'Voucher No', subq.Voucher_Type 'Voucher Type', case when subq.deb>0 then subq.deb else '' end as Debit, case when subq.cred>0 then subq.cred else '' end as Credit FROM ( SELECT Against_Ledger, SUM(Credit_Amount-Debit_Amount) as cred, SUM(Debit_Amount-Credit_Amount) as deb,Voucher_Date, Voucher_ID,  Voucher_Type, Voucher_Prefix From Transaction_Helper Where Ledger_ID='0x2x15A95' AND Voucher_Date >=str_to_date('$fromDateTime','%Y-%m-%d') AND Voucher_Date  <=str_to_date('$toDateTime','%Y-%m-%d') AND ( case when Voucher_Type = 'SalesVoucher' then Voucher_ID in  ( SELECT Voucher_No from Sales_Invoice_Main Where POC_Phone = '$f1') when Voucher_Type = 'PurchaseVoucher' then Voucher_ID in  ( SELECT Voucher_No from Purchase_Invoice_Main Where POC_Phone = '$f1') when Voucher_Type = 'PaymentVoucher' then  Voucher_ID in  ( SELECT Voucher_No from Payment_Voucher_Main Where POC_Phone = '$f1') when Voucher_Type = 'ReceiptVoucher' then Voucher_ID in ( SELECT Voucher_No from  Receipt_Voucher_Main Where POC_Phone = '$f1') end ) GROUP BY Voucher_ID, Voucher_Type ORDER BY Voucher_Date, Voucher_ID, Voucher_Type ) subq UNION SELECT 'V' as Ind, so.Voucher_No, so.Voucher_Prefix, 'SalesOrder', (select ledger_name from $master_db.ledger_master where ledger_id = so.ledger_id) as Ledger,  so.Voucher_Date,  so.Voucher_No, 'SALES ORDER', cast(so.Total as decimal(10,2)) as Debit, 0 as Credit  FROM Sales_Order_Main so Where POC_Phone = '$f1' AND  so.Voucher_Date  >=str_to_date('$fromDateTime','%Y-%m-%d') AND so.Voucher_Date  <=str_to_date('$toDateTime','%Y-%m-%d') AND so.VoucherStatus  < 170) A order by 1