Business Analytics · Problem 90 of 118

Loan Repayment Status

MediumBusiness AnalyticsBank data

For loans whose status is not 'paid_off', return loan_id, status, payments (the number of payments made) and paid_cents (the sum of amount_cents paid, 0 if none). Show the five loans with the highest paid_cents; sort by paid_cents from high to low, then loan_id.

Hint 1

LEFT JOIN loan_payments keeps loans without payments; count a column of the payments table so those show 0.

Reference solution

SELECT l.loan_id,
       l.status,
       COUNT(p.payment_id) AS payments,
       COALESCE(SUM(p.amount_cents), 0) AS paid_cents
FROM loans AS l
LEFT JOIN loan_payments AS p ON p.loan_id = l.loan_id
WHERE l.status <> 'paid_off'
GROUP BY l.loan_id, l.status
ORDER BY paid_cents DESC, l.loan_id
LIMIT 5;

SUM of nothing is NULL, not 0, so a loan without payments needs COALESCE(SUM(...), 0) to show zero. A LEFT JOIN is the right tool whenever "no related rows" is a meaningful answer rather than a reason to drop the row. Here the filter is on the left table (l.status), so it can safely sit in WHERE.