select
    pi.identifier as 'Patient Id',
    CONCAT(IF(pn.given_name is null, '', CONCAT((pn.given_name), ' ')), IF(pn.family_name is null, '', CONCAT((pn.family_name), ' '))) as 'Patient name',
    p.gender as 'Gender',
    p.birthdate as 'Birth Date',
    pa.value as 'Phone Number',
    v.date_created as 'Visited Date',
    user.username as 'Created By',
    u.username as 'Visited By'
from obs as o
         inner join concept_view as cv on cv.concept_id = o.value_coded
         inner join person p on p.person_id=o.person_id
         inner join person_name as pn on pn.person_id = p.person_id
         inner join encounter e on o.encounter_id = e.encounter_id
         inner join visit v on e.visit_id = v.visit_id
         inner join visit_type vt on v.visit_type_id = vt.visit_type_id
         inner join patient_identifier as pi on pi.patient_id = p.person_id
         inner join users as user on user.user_id = v.creator
         inner join users as u on u.user_id = o.creator
         left join person_attribute as pa on p.person_id = pa.person_id and pa.person_attribute_type_id=(select pat.person_attribute_type_id from person_attribute_type as pat where pat.name='phoneNumber')
where
    o.concept_id = (select conv.concept_id from concept_view as conv where concept_full_name = 'Registration Patient Category')
    and o.voided=0
  and pi.identifier_type=(select pit.patient_identifier_type_id from patient_identifier_type as pit where pit.name='Patient Identifier')
    and cast(o.date_created as DATE) between '#startDate#' AND '#endDate#'
    and vt.name='outpatient'
order by user.username;
