SELECT 'V' as Ind, RefNo, RefPrefix, RefType, min(VoucherDate) as 'Voucher Date', RefNo as 'Voucher No', RefType as 'Voucher Type', (select sum(DebitAmount - creditAmount) from $trans_db.billwise_records where voucherNo = Ref.RefNo AND voucherType = Ref.RefType AND voucherPrefix = Ref.RefPrefix) as 'Bill Amount', SUM(COALESCE(DebitAmount,0)) -  SUM(COALESCE(CreditAmount,0)) as 'Balance Amount'  FROM $trans_db.Billwise_Records Ref WHERE Ref.LedgerId = '$f1' AND Ref.VoucherDate <= str_to_date('$toDateTime','%Y-%m-%d %H:%i:%s') AND (Method_Of_Adj<> 'ON ACC' OR Method_Of_Adj IS NULL) GROUP BY RefNo, RefType, RefPrefix HAVING SUM(COALESCE(CreditAmount,0)) - SUM(COALESCE(DebitAmount,0)) <> 0 ORDER BY 1