DELIMITER $$

create ALGORITHM=UNDEFINED DEFINER=`apzl`@`%` SQL SECURITY DEFINER VIEW `vi_splitting_pay` AS (
SELECT O.distributor_id,
O.CONTRACT_NO,
O.contract_id,
O.lccc_charge,
O.lccc_ratio,
O.lccc_list,
O.plan_list,
lul.customer_name,
lrp.interest_sp AS sum_sp,IFNULL(lsp.splitting_money,0) AS splitting_money,lrp.interest_sp*O.lccc_ratio/100 AS should_sp, lrp.interest_sp*O.lccc_ratio/100-IFNULL(lsp.splitting_money,0) AS cur_sp
FROM vi_split_config O 
LEFT JOIN (SELECT SUM(interest_sp) AS interest_sp,contract_id FROM lc_rent_plan WHERE interest_sp IS NOT NULL GROUP BY contract_id) lrp 
	ON lrp.contract_id=O.contract_id 
LEFT JOIN (SELECT SUM(IFNULL(splitting_money,0)) AS splitting_money,contract_id,MAX(pay_list) AS pay_list,id FROM lc_splitting_pay GROUP BY contract_id) lsp 
	ON O.contract_id=lsp.contract_id AND O.lccc_charge=lsp.pay_list
LEFT JOIN lb_union_lessee lul
      ON lul.CONTRACT_ID = O.contract_id AND lul.IS_MAIN = 'Y'
WHERE lsp.id IS NULL AND O.lccc_charge>0

)$$

DELIMITER ;