如图:按arrair_id分组,
如果,组内有为chang_type =1的,则取最新一个change_type=1的金额,
否则,组内金额求和sum
sql实现如下
select
count(ci.id) as count-- 合同数量
,if(
locate('1',GROUP_CONCAT(change_type order by ci.create_time desc)) >0 -- 如果,有变更时
, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(money order by ci.create_time desc),',',locate('1',GROUP_CONCAT(change_type order by ci.create_time desc separator ''))),',',-1) -- 取最后一次变更金额
, sum(cf.money) -- 否则,金额的和
)
from contract_instance ci
left join contract_finance cf on cf.contract_id = ci.id
where ci.delete_flag = 0
group by ci.arrair_id -- 业务id分组