Хорошо, давайте попробуем это:
select
NOT_FILETM_LOC_DTTM as documented_date
, HNO_INFO.pat_enc_csn_id,
AUTHOR_USER_ID, emp."NAME" as md,patient.pat_id,hno_note_text.note_text, pat_mrn_id
, cast(NOT_FILETM_LOC_DTTM as date) - cast( patient.birth_date as date) year (4) as age
, department_name unit
, adt.event_id
from HNO_INFO
, hno_note_text
, NOTE_ENC_INFO
, clarity_emp emp
, patient
, pat_enc_hsp
,clarity_dep
--, clarity_adt
,(select max(event_id) event_id, adt.pat_enc_csn_id, department_id, effective_time from clarity_adt adt
where adt.EVENT_SUBTYPE_C <> 2 and adt.event_type_c<>6
group by adt.pat_enc_csn_id, department_id, effective_time
) adt
where
NOTE_ENC_INFO.note_id = HNO_INFO.note_id
and adt.department_id = clarity_dep.department_id
and pat_enc_hsp.pat_enc_csn_id = adt.pat_enc_csn_id
and adt.effective_time <= NOT_FILETM_LOC_DTTM
and hno_note_text.note_id = HNO_INFO.note_id
and hno_note_text.note_text like ('%Procedural Sedation Stop Time:%')
and (hno_note_text.note_text like ('%PICC%') or hno_note_text.note_text like ('%Lumbar Puncture%'))
and emp.user_id = AUTHOR_USER_ID
and patient.pat_id = HNO_INFO.pat_id
and pat_enc_hsp.pat_enc_csn_id = HNO_INFO.pat_enc_csn_id
and cast(documented_date as date) >= '2018-01-01'
qualify row_number() over (partition by HNO_INFO.pat_enc_csn_id order by documented_date )=1
;