Hi,
I have this sql
Select DISTINCT p.dbPatID, p.dbpatfirstname, p.dbPatLastName, s.dbSchTypeCnt as SchDetailType, t.dbSchTypeCnt as SchTypeType, ISNULL(r.dbStatusDesc, 'No Ref') AS dbStatusDesc, ISNULL(t.dbSchTypeCode, 'No Ref') AS dbSchTypeCode, ISNULL(t.dbSchTypeDesc, 'No Ref') AS dbSchTypeDesc, p.dbProgRvw, ISNULL(s.dbSchDate, '1899-12-30') AS dbSchDate, ISNULL(s.dbSchTypeCnt, '0') AS dbSchTypeCnt, p.age, ISNULL(rc.dbRecDate, '1899-12-30') AS dbRecDate, ISNULL(rc.dbRecType, '-') AS dbRecType, ISNULL(rc.dbRecCom, '-') AS dbRecCom, a.dbPatApptTime as LastVisitDate, a.dbSchTypeDesc as LastVisitDesc FROM Patient p LEFT OUTER JOIN vw_ReferralKPIs r ON p.dbpatid = r.dbPatID AND r.ClientRef = p.ClientRef LEFT OUTER JOIN SchDetail s on s.dbPatCnt = p.dbPatCnt AND s.ClientRef = p.ClientRef LEFT OUTER JOIN SchTypes t on s.dbSchTypeCnt = t.dbSchTypeCnt AND t.ClientRef = p.ClientRef LEFT OUTER JOIN Recalls rc on p.dbpatcnt = rc.dbpatcnt AND rc.ClientRef = p.ClientRef LEFT OUTER JOIN Appointments a on p.dbpatcnt = a.dbpatcnt AND rc.ClientRef = a.ClientRef AND dbPFStatus = 1 Where (r.dbStatusDesc IN ('') OR '' = '') AND s.dbSchDate <= GetDate() AND p.ClientRef = 'EPS' AND r.dbStatusDesc != 'Discharged' AND r.dbStatusDesc != 'TC Disch' AND r.dbStatusDesc != 'Discharge FTA'
I've added the Appointments join code as we need LastVisitDate and LastVisitDesc but we only wish to bring back the row from Appointments that has the max date (latest date).
If I add a temp Where clause 'AND p.dbPatCnt = 9678', it brings back 12 rows (all that person's appointments where dbPFStatus =1) I only want to bring back the row that has the latest date.
thanks,