SELECT pi.identifier                                                           as 'Patient ID',
       CONCAT(IF(pn2.given_name IS NULL, '', CONCAT((pn2.given_name), ' ')),
              IF(pn2.middle_name IS NULL, '', CONCAT((pn2.middle_name), ' ')),
              IF(pn2.family_name IS NULL, '', CONCAT((pn2.family_name), ' '))) AS 'Patient Name',
       per.gender                                                              as 'Gender',
       TIMESTAMPDIFF(YEAR, per.birthdate, CURDATE())                           AS 'Age',
       CONCAT(IF(pn.given_name IS NULL, '', CONCAT((pn.given_name), ' ')),
              IF(pn.middle_name IS NULL, '', CONCAT((pn.middle_name), ' ')),
              IF(pn.family_name IS NULL, '', CONCAT((pn.family_name), ' ')))   AS 'Consulted By'
FROM encounter e
         INNER JOIN encounter_provider ep on ep.encounter_id = e.encounter_id
         INNER JOIN provider p on p.provider_id = ep.provider_id and p.retired = 0
         INNER JOIN person_name pn on p.person_id = pn.person_id
         inner join patient_identifier as pi on e.patient_id = pi.patient_id and
                                                pi.identifier_type = (select patient_identifier_type_id
                                                                      from patient_identifier_type
                                                                      where name = 'Patient Identifier')
         inner join person_name as pn2 on pn2.person_id = pi.patient_id
         inner join person as per on per.person_id = pn2.person_id and per.voided = 0
WHERE e.encounter_type in
      (select encounter_type_id from encounter_type where name in ("EME", "Consultation", "OPD", "IPD"))
  and cast(e.encounter_datetime as date) BETWEEN '#startDate#' AND '#endDate#';
