Hi,
I have the following SQL View which is working but very slow - please could you advise how can receive the same output more quickly. The select statement needs to be re-designed.
CREATE VIEW [COM].[OSR_TEMPLATE_Pat_201711]
AS
WITH TimesliceRecords AS
(
SELECT
p.PatientKey,
p.PatientIdentifier AS patid,
p.CPRDPracticeId AS pracid,
UsualGPStaffID AS usualgpstaffid,
GenderId AS gender,
YearOfBirth AS yob,
MonthOfBirth AS mob,
FROM [Committed].[Clinical_Patient] p WITH (NOLOCK)
LEFT OUTER JOIN [COMMITTED].[D_Patients_On_Date]('20171101') dp ON p.PatientIdentifier = dp.PatientIdentifier AND p.CPRDPracticeId = dp.CPRDPracticeId
WHERE p.RowStartDate <= '20171101' AND COALESCE(p.RowEndDate,'99991231') > '20171101'
AND dp.PatientIdentifier IS NULL
AND p.IsAcceptable = CONVERT(BIT,1)
)
SELECT
t.patid,
t.pracid,
t.usualgpstaffid,
t.gender,
t.yob,
t.mob,
FROM
TimesliceRecords t
WHERE
t.PatientKey = (SELECT MAX(t1.PatientKey) FROM TimesliceRecords t1 WHERE t.patid=t1.patid)
Without the second SELECT statement to the query it runs instantly. Any advice will be appreciated.
Thank you