Question : how to change sql query not to pull duplicates

I have a view that is checking to see if patients are on certain meds but I only want to show each patient once. If they are on multiple meds I only want to include the one that has the most recent pm.start_date.

ALTER view [dbo].[meds]
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'))

Answer : how to change sql query not to pull duplicates

You could try like this:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
;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)
Random Solutions  
 
programming4us programming4us