create function getRemainInterest(p_payment_number varchar(40), p_plan_list int, remain_type varchar(40)) returns decimal(18,2)
RETURN 
(
select 
case when remain_type='interest'
then
scrm.si-listcrm.si 
when  remain_type='fee' then
scrm.sf-listcrm.sf
when
 remain_type='discount'
then scrm.sd-listcrm.sd 
else 0 end 
from
(SELECT contract_id,
SUM(interest) si,SUM(fee) sf, SUM(discount) sd
FROM contract_rent_month 
where payment_number = p_payment_number 
)
scrm 
LEFT JOIN (SELECT contract_id,
SUM(interest) si,SUM(fee) sf, SUM(discount) sd
FROM contract_rent_month WHERE  payment_number = p_payment_number and rent_list<=p_plan_list )
listcrm ON listcrm.contract_id=scrm.contract_id);

