sounds like this:-select a.first_name,a.last_name,cast(a.date_of_birth as datetime) as PtDOB,cast(MAX(CASE WHEN c.appt_date <= getdate() THEN c.appt_date ELSE NULL END) as datetime) as dateoflastvisit,cast(MIN(CASE WHEN c.appt_date > getdate() THEN c.appt_date ELSE NULL END) as datetime) as dateofnextvisitfrom person ajoin hiv_flowsheet_ b on a.person_id = b.person_idjoin appointments c on b.person_id = c.person_idjoin provider_mstr d on c.rendering_provider_id = d.provider_idwhere d.description like '%applin%' group by a.first_name,a.last_name,cast(a.date_of_birth as datetime)