Reputation: 1267
I have the following db schema (i'm only mentioning the columns for each table necessary for the query in mind):
bills
-------
id
amount (decimal)
collection_case_id
collection_case
------------------
id
payments
----------
id
bill_id
amount (decimal)
type (char(2)) - "CH" stands for check payment, field used for polymorphism
check_payments
---------------
payment_id
For a set of collection cases, I need to get the total interest earned from check payments. I am currently doing these calculations in memory after retrieving all the bill records for my set of collection case criteria. For each bill I simply add the sum of checks received - bill amount if sum of checks received is greater than bill amount.
for instance my total received query looks like this (collection cases 1 & 2):
select sum(payment.amount) as received
from bills bill
cross join payments payment inner join check_payments checkpayment
on
payment.id=checkpayment.payment_id
where payment.type='CH'
and payment.bill_id=bill.id
and (bill.collection_case_id in (1 , 2))
Upvotes: 0
Views: 83
Reputation: 4957
Not really sure if this is what you meant.
select IF(sum(payment.amount) > bill.amount, sum(payment.amount)-bill.amount, 0) as interest
from bills bill
cross join payments payment inner join check_payments checkpayment
on
payment.id=checkpayment.payment_id
where payment.type='CH'
and payment.bill_id=bill.id
and (bill.collection_case_id in (1 , 2))
Upvotes: 1