;with CTE as (
SELECT p.last_name,
p.first_name,
p.person_id,
pe.enc_id,
pe.enc_timestamp,
pm.start_date,
pm.date_stopped,
pm.date_last_refilled,
fm.brand_name,
fm.generic_name,
fm.dose
FROM patient_medication pm with (nolock)
INNER JOIN fdb_medication fm with (nolock) ON pm.ndc_id = fm.ndc_id
INNER JOIN patient_encounter pe with (nolock) on pm.enc_id = pe.enc_id
inner join person p on pe.person_id = p.person_id
WHERE
((pm.date_stopped = '' OR pm.date_stopped is null)or (pm.date_stopped > getdate
and (fm.generic_name IN ('HYDROCODONE BIT/ACETAMINOPHEN', 'OXYCODONE HCL/ACETAMINOPHEN'))
)
select a.* from CTE a
where a.start_date = (select max(start_date) from CTE where person_id = a.person_id)
|