помогите оптимизировать пожалуйста, запрос работает, но жрёт много ресурсов.
select DocumentNodeValue CauseZatrimka2, patientref, CourseID, DocumentCreationDate from
(
select max(DocumentNodeID) CauseVipiska
,patientref, courseID, DocumentCreationDate from DocumentNode join Document on DocumentID = DocumentRef join Course on CourseID = CourseRef
where DocumentNodeStaticGUIDRef = 'cb8e5dcd-4932-4fb1-a2c3-5a357a3853ac'
and
DocumentNodeID not in ( select max(DocumentNodeID) from DocumentNode
where DocumentNodeStaticGUIDRef = 'cb8e5dcd-4932-4fb1-a2c3-5a357a3853ac'
group by DocumentRef)
group by DocumentRef, patientref, courseID, DocumentCreationDate
having DocumentCreationDate in (select max(DocumentCreationDate) CauseVipiska
from DocumentNode join Document on DocumentID = DocumentRef join Course on CourseID = CourseRef
where DocumentNodeStaticGUIDRef = 'cb8e5dcd-4932-4fb1-a2c3-5a357a3853ac'
and
DocumentNodeID not in ( select max(DocumentNodeID) from DocumentNode
where DocumentNodeStaticGUIDRef = 'cb8e5dcd-4932-4fb1-a2c3-5a357a3853ac'
group by DocumentRef)
group by courseID
)
суть запроса в том, что нужно выбрать предпоследний документ по дате создания