(select vt.name                                    AS 'Visit Type',
        rag.name                                   AS 'Patient Age Group',
        sum(IF(p.gender = 'M', 1, 0))              AS Male,
        sum(IF(p.gender = 'F', 1, 0))              AS Female,
        sum(IF(p.gender = 'O', 1, 0))              AS Other,
        sum(IF(p.gender in ('F', 'M', 'O'), 1, 0)) AS Total
 from (select o.person_id, o.date_created
       from obs o
       where o.voided = 0
         and o.concept_id in
             (select cv.concept_id from concept_view cv where concept_full_name = 'Registration Patient Category')
         and cast(o.obs_datetime as DATE) between '#startDate#' AND '#endDate#'
       group by o.person_id, cast(o.obs_datetime as date)) obs_value
          inner join person p on obs_value.person_id = p.person_id and p.voided = 0
          inner join reporting_age_group rag ON
             rag.min_years <= TIMESTAMPDIFF(YEAR, p.birthdate, obs_value.date_created) and
             rag.max_years >= TIMESTAMPDIFF(YEAR, p.birthdate, obs_value.date_created)
         AND rag.report_group_name = 'Registration'
          inner join visit as v on obs_value.person_id = v.patient_id and v.voided = 0
          inner join visit_type as vt on vt.visit_type_id = v.visit_type_id
 group by vt.name, rag.name, rag.sort_order
 ORDER BY rag.sort_order)
union all
(select vt.name as 'Visit Type',
        'Total Patient',
        '',
        '',
        '',
        count(obs_value.person_id)
 from (select o.person_id, o.date_created
       from obs o
       where o.voided = 0
         and o.concept_id in
             (select cv.concept_id from concept_view cv where concept_full_name = 'Registration Patient Category')
         and cast(o.obs_datetime as DATE) between '#startDate#' AND '#endDate#'
       group by o.person_id, cast(o.obs_datetime as DATE)) obs_value
          inner join visit as v on obs_value.person_id = v.patient_id and v.voided = 0
          inner join visit_type as vt on vt.visit_type_id = v.visit_type_id
 group by vt.name);
