I have a LOAN table (LOAN) with the following fields:
[ul]pk, loan_no, loan_value, loan_status[/ul]
Loans are of LIVE (L) status until they have been fully paid, at which point their status changes to REPAID (R).
I also have a CASH table (CASH) which holds information about lumps of cash ('Reservations') that are sitting in accounts, waiting to be used to pay (or part-pay) loans at a later date. Reservations that are linked to a loan and are waiting to be used have an ASSIGNED (A) status. Once the reservations have been paid into the loan account their status changes to PAID (P). Information held is as follows:
[ul]pk, fk_loan, res_value, res_status[/ul]
Crucially we can part-pay a loan, transferring some of the Reservations but not others. This means that we can have loans of LIVE status that have several reservations, some of which are ASSIGNED, others of which are PAID. I need to write a select statement that will show all loans (Live and Repaid) and the sum of their *Assigned* reservations.
I started with this:
But the problem with this is that the sum(CASH.res_value) is summing all res_value records, whereas I want to exclude res_value records that are of PAID status. So then I tried adding a WHERE clause like this:
This does now give me the desired SUM totals, but unfortunately it also filters out any loans that don't have any Reservations of Assigned (A) status. To be clear, I want to show all loans, regardless of the status of their linked Reservations, I just want to exclude Paid reservations from the sum. I can see why both my examples aren't giving me what I want, but is there a way of doing this?
Tom
[ul]pk, loan_no, loan_value, loan_status[/ul]
Loans are of LIVE (L) status until they have been fully paid, at which point their status changes to REPAID (R).
I also have a CASH table (CASH) which holds information about lumps of cash ('Reservations') that are sitting in accounts, waiting to be used to pay (or part-pay) loans at a later date. Reservations that are linked to a loan and are waiting to be used have an ASSIGNED (A) status. Once the reservations have been paid into the loan account their status changes to PAID (P). Information held is as follows:
[ul]pk, fk_loan, res_value, res_status[/ul]
Crucially we can part-pay a loan, transferring some of the Reservations but not others. This means that we can have loans of LIVE status that have several reservations, some of which are ASSIGNED, others of which are PAID. I need to write a select statement that will show all loans (Live and Repaid) and the sum of their *Assigned* reservations.
I started with this:
Code:
SELECT LOAN.loan_no, LOAN.loan_value, sum(CASH.res_value) as total_assigned
FROM LOAN
INNER JOIN CASH on LOAN.pk = CASH.fk_loan
GROUP BY LOAN.loan_no, LOAN.loan_value
Code:
SELECT LOAN.loan_no, LOAN.loan_value, sum(CASH.res_value) as total_assigned
FROM LOAN
INNER JOIN CASH on LOAN.pk = CASH.fk_loan
WHERE CASH.res_status = 'A'
GROUP BY LOAN.loan_no, LOAN.loan_value
Tom