我有以下数据库模式(我只提到查询所需的每个表的列):
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
对于一组收款案例,我需要获取从支票付款中获得的总利息。在为我的收款案例标准集检索所有账单记录后,我目前正在内存中进行这些计算。对于每张账单,我只需添加收到的支票总和 - 如果收到的支票总和大于账单金额,则账单金额。
例如,我收到的总查询如下所示(收集案例 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))