#This is a mysql syntax highlighter -- This is a comment /* And this is a multi line comment SELECT things FROM table; */ SELECT ag.name AS agent, `d.date`, d.first_payment_date, d.account_number, d.id as disbursement_id, d.amount as loan_amount, d.late_fee, b.id as bid, b.name as borrower, tf.name as payment_frequency, ap.id as application_id, (SELECT COUNT(id) FROM payment_schedule WHERE disbursement_id = d.id AND skip = '1') as skip_count, IFNULL(SUM(r.principal), 0) as paid_principal, IF(d.interest_calculation_method_id = 2, d.amount, IFNULL((SELECT SUM(principal) FROM payment_schedule WHERE disbursement_id = d.id AND skip = '0' AND date <= CURDATE()), 0)) as psprincipal, IF(d.interest_calculation_method_id IN(2, 3), d.amount - (SELECT IFNULL(SUM(principal), 0) FROM receipts WHERE disbursement_id = d.id), IFNULL((SELECT SUM(principal+interest) FROM payment_schedule WHERE disbursement_id = d.id AND skip = '0' AND date <= CURDATE()), 0)) as psamount, FROM disbursements d LEFT JOIN receipts r ON r.disbursement_id=d.id LEFT JOIN applications ap ON d.application_id = ap.id LEFT JOIN agents ag ON ap.vt_user_id = ag.vt_user_id LEFT JOIN borrowers b ON ap.borrower_id = b.id LEFT JOIN time_frequencies tf ON d.payment_frequency_id = tf.id WHERE d.status = 'active' ORDER BY due_date