Zazwyczaj używa się row_number()
:
select id, name, visit_date as first_visit_date, reference_number
from (select v.id, p.name, v.visit_date, v.reference_number,
row_number() over (partition by p.id order by v.visit_date desc) as seqnum
from visits v join
patients p
on v.patient_id p.id
) t
where seqnum = 1;