set @ds1:='2012-10-1';
set @ds2:='2013-9-30';
select cast(a.village_moo as decimal) moo,a.village_name name,b.*
,if(b.target=0,0,b.total/b.target*100) percent
from village a
left join (select v.village_id
,count(distinct p.cid) target
,count(distinct if(s.women_service_id=1 and s.women_birth_control_id>0,s.person_women_service_id,null)) total
,count(distinct if(s.women_birth_control_id=0 or s.women_birth_control_id is null,s.person_women_service_id,null)) FP0
,count(distinct if(s.women_birth_control_id=1,s.person_women_service_id,null)) FP1
,count(distinct if(s.women_birth_control_id=2,s.person_women_service_id,null)) FP2
,count(distinct if(s.women_birth_control_id=3,s.person_women_service_id,null)) FP3
,count(distinct if(s.women_birth_control_id=4,s.person_women_service_id,null)) FP4
,count(distinct if(s.women_birth_control_id=5,s.person_women_service_id,null)) FP5
,count(distinct if(s.women_birth_control_id=6,s.person_women_service_id,null)) FP6
,count(distinct if(s.women_birth_control_id=7,s.person_women_service_id,null)) FP7
from person p
left join village v on p.village_id=v.village_id
left join person_women w on p.person_id=w.person_id
left join person_women_service s on w.person_women_id=s.person_women_id and s.service_date between @ds1 and @ds2 and s.women_service_id=1
where p.sex=2
and p.marrystatus=2
and p.house_regist_type_id in (1,3)
and timestampdiff(year,p.birthdate,@ds1) between 15 and 44
group by v.village_id) b on a.village_id=b.village_id
order by 1