with clean_table as
(SELECT distinct * FROM `tbl_emp_leave_dm`
where fld_approval_status = 'APPROVED'
      and fld_leave_start_date <= cast('{0}' as date)
)
,
table1 as (
      select fld_employee_id
      ,fld_time_type
      ,fld_day_type
      ,fld_country
      ,fld_quantity_in_days
      ,fld_leave_start_date
      ,if(fld_leave_end_date > cast("{0}" as date), 
          cast("{0}" as date), fld_leave_end_date)
          as fld_leave_end_date
      ,if(fld_leave_end_date > cast("{0}" as date), 
          1, 0)
          as adjusted_end_date
from clean_table)
,
table2 as
(select * from table1
where fld_leave_end_date >= cast("{1}" as date)
)
select fld_employee_id
      ,fld_time_type
      ,fld_day_type
      ,fld_country
      ,fld_quantity_in_days
      ,if(fld_leave_start_date < cast("{1}" as date),
          cast("{1}" as date), fld_leave_start_date)
      as fld_leave_start_date
      ,fld_leave_end_date
      ,adjusted_end_date
      ,if(fld_leave_start_date < cast("{1}" as date),
          1,0) as adjusted_start_date
from table2
