• I'm sure you can clean this up but it will do what you want.

    ; with cte

    as

    (select d.idxmrn, d.dischargedate, a.apptdt2, DATEDIFF(d,d.dischargedate, a.apptdt2) daysSince, ROW_NUMBER() over (PARTITION by d.idxmrn order by d.idxmrn,DATEDIFF(d,d.dischargedate, a.apptdt2)) as rownum

    from discharges d

    inner join appointments a

    on d.idxmrn = a.idxmrn

    group by d.idxmrn, d.dischargedate, a.apptdt2

    having MAX(d.dischargedate)<MIN(a.apptdt2)

    )

    select * from cte where rownum = 1