SELECT admit.date                  as 'Date',
       admit.ward_name             as 'Ward Name',
       admit.admit_patient         as 'Admitted Patient',
       discharge.discharge_patient as 'Discharge Patient'
FROM (SELECT cast(e.encounter_datetime as date) as 'date',
             ward.name                          as 'ward_name',
             count(bed_assign.patient_id)       as 'admit_patient'
      FROM encounter e
               inner join (select bpam.patient_id, bpam.date_created, bpam.bed_id, bpam.encounter_id
                           from bed_patient_assignment_map bpam
                           where bpam.date_created between '#startDate#' AND '#endDate#'
                           group by bpam.patient_id, cast(bpam.date_created as date)) bed_assign
                          on bed_assign.encounter_id = e.encounter_id
               inner join bed_location_map blm on bed_assign.bed_id = blm.bed_id
               inner join location as ward on blm.location_id = ward.location_id
      WHERE e.encounter_type in
            (select encounter_type_id from encounter_type where name in ('ADMISSION'))
        and e.encounter_datetime BETWEEN '#startDate#' AND '#endDate#'
      group by date, ward.name) as admit
         left join (SELECT cast(e.encounter_datetime as date) as 'date',
                           ward.name                          as 'ward_name',
                           count(bed_assign.patient_id)       as 'discharge_patient'
                    FROM encounter e
                             inner join (SELECT bed_patient_assignment_map_id, bed_id, patient_id
                                         FROM bed_patient_assignment_map
                                         WHERE bed_patient_assignment_map_id IN (
                                             SELECT MAX(bed_patient_assignment_map_id)
                                             FROM bed_patient_assignment_map
                                             GROUP BY patient_id)) bed_assign on e.patient_id = bed_assign.patient_id
                             inner join bed_location_map blm on bed_assign.bed_id = blm.bed_id
                             inner join location as ward on blm.location_id = ward.location_id
                    WHERE e.encounter_type in
                          (select encounter_type_id from encounter_type where name in ('DISCHARGE'))
                      and e.encounter_datetime BETWEEN '#startDate#' AND '#endDate#'
                    group by date, ward.name) as discharge
                   on admit.date = discharge.date and admit.ward_name = discharge.ward_name;
