SELECT iv.id,
b.name AS biller,
c.name AS customer,
(SELECT SUM(coalesce(ii.total, 0)) FROM si_invoice_items ii WHERE ii.invoice_id = iv.id) AS invoice_total,
(SELECT SUM(coalesce(ac_amount, 0)) FROM si_account_payments ap WHERE ap.ac_inv_id = iv.id) AS INV_PAID,
(SELECT (coalesce(invoice_total,0) - coalesce(INV_PAID,0))) As owing,
DATE_FORMAT(date,'%Y-%m-%d') AS date,
(SELECT IF((owing = 0), 0, DateDiff(now(), date))) AS Age,
(SELECT (CASE WHEN Age = 0 THEN ''
WHEN Age <= 14 THEN '0-14'
WHEN Age <= 30 THEN '15-30'
WHEN Age <= 60 THEN '31-60'
WHEN Age <= 90 THEN '61-90'
ELSE '90+' END)) AS aging,
iv.type_id As type_id,
pf.pref_description AS preference
FROM si_invoices iv
LEFT JOIN si_biller b ON b.id = iv.biller_id
LEFT JOIN si_customers c ON c.id = iv.customer_id
LEFT JOIN si_preferences pf ON pf.pref_id = iv.preference_id
1 to 6 of 6