select hospital_code, count(*) as total, sum(more_25), sum(between_18_24), sum(between_15_17), sum(less_15) from (select concat(city_code,'/',hospital_code) as hospital_code, session.id_patient, if(timestampdiff(year,dob,date)>=25 or dob = '0000-00-00',1,0) as more_25, if(timestampdiff(year,dob,date) between 18 and 24,1,0) as between_18_24, if(timestampdiff(year,dob,date) between 15 and 17,1,0) as between_15_17, if(timestampdiff(year,dob,date) <15,1,0) as less_15 from session left join club_session on id_club_session=club_session.id left join club on club.id=id_club left join lookup_hospital on id_hospital=lookup_hospital.id left join tracking_motherbasicinfo on tracking_motherbasicinfo.id_patient=session.id_patient where club_type=1 and is_present=1 and date between '2017-04-01' and '2017-09-30' and session.id_patient in (select id from patient) group by session.id_patient)x group by hospital_code
Comments