I need help with the below mentioned query ... In particular, this section of code: ( SELECT TOP 1 pvp.CPTCode FROM PatientVisit pv INNER JOIN PatientVisitProcs pvp ON pv.patientvisitid = pvp.patientvisitid WHERE pvp.listorder = 1 AND pv.patientvisitid = pvp.patientvisitid AND pp.PatientProfileId = pv.PatientProfileId AND pv.Visit < DATEADD(day , 1 , ISNULL(GETDATE() , '1/1/3000')) ) AS LastProcedure
I am getting results in the field, however the results are not what they should be. I am getting a value, but not the right value. Its giving me the CPTCode from someone elses visit. I must have a join condition wrong somwhere in this. My full query is below ... Full Query:/* Recall Letters */SET NOCOUNT ONSELECT r.[Date], pp.Prefix AS PatientPrefix, pp.[First] AS PatientFirst, pp.[Last] AS PatientLast, ( SELECT TOP 1 ISNULL(CONVERT(VARCHAR(20) , pv.Visit , 101) , '') FROM PatientVisit pv WHERE pv.PatientProfileId = pp.PatientProfileId AND pv.Visit < DATEADD(day , 1 , ISNULL(GETDATE() , '1/1/3000')) ORDER BY pv.Visit DESC ) AS LastVisit, ( SELECT TOP 1 pvp.CPTCode FROM PatientVisit pv INNER JOIN PatientVisitProcs pvp ON pv.patientvisitid = pvp.patientvisitid WHERE pvp.listorder = 1 AND pv.patientvisitid = pvp.patientvisitid AND pp.PatientProfileId = pv.PatientProfileId AND pv.Visit < DATEADD(day , 1 , ISNULL(GETDATE() , '1/1/3000')) ) AS LastProcedure, df.[First] AS DoctorFirst, df.[Last] AS DoctorLast, df.Suffix AS DoctorSuffix, '(' + SUBSTRING(df.Phone1 , 1 , 3) + ') ' + SUBSTRING(df.Phone1 , 4 , 3) + '-' + SUBSTRING(df.Phone1 , 7 , 4) AS DoctorPhone, df2.Address1 AS DoctorAddr1, df2.Address2 AS DoctorAddr2, df2.City AS DoctorCity, df2.State AS DoctorState, df2.Zip AS DoctorZip, pp.Address1 AS PatientAddr1, pp.Address2 AS PatientAddr2, pp.City AS PatientCity, pp.State AS PatientState, pp.Zip AS PatientZip, g.Prefix AS PatientRespPrefix, g.[First] AS PatientRespFirst, g.[Last] AS PatientRespLast, g.Address1 AS PatientRespAddr1, g.Address2 AS PatientRespAddr2, g.City AS PatientRespCity, g.State AS PatientRespState, g.Zip AS PatientRespZip, pp.PatientSameAsGuarantor AS RespSameAsPatient, r.DoctorResourceId, r.FacilityId, ISNULL(at.Name , ' ') AS AppointmentTypeFROM Recall r INNER JOIN PatientProfile pp ON r.PatientProfileId = pp.PatientProfileId LEFT OUTER JOIN ApptType at ON r.ApptTypeId = at.ApptTypeId LEFT OUTER JOIN DoctorFacility df ON r.DoctorResourceId = df.DoctorFacilityId LEFT OUTER JOIN DoctorFacility df2 ON r.FacilityId = df2.DoctorFacilityId LEFT OUTER JOIN Guarantor g ON pp.GuarantorId = g.GuarantorIdWHERE r.ApptId IS NULL AND r.Date >= ISNULL(NULL , '1/1/1900') AND r.Date < DATEADD(d , 1 , ISNULL(NULL , '1/1/3000')) AND --Filter on resource ( ( NULL IS NOT NULL AND r.DoctorResourceID IN ( NULL ) ) OR ( NULL IS NULL ) ) AND --Filter on facility ( ( NULL IS NOT NULL AND r.FacilityID IN ( NULL ) ) OR ( NULL IS NULL ) ) AND --Filter on Inactive ISNULL(r.inactive , 0) = 0ORDER BY ISNULL(g.Last , '') + ISNULL(g.First , '')