Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Multiple conditions where clause the same column

Tags:

sql

I have a dataset that looks a little something like this

Subject_ID   Diagnosis_ID  
001          299
001          288
001          233
001          299
002          299
002          233
003          238
004          299
004          233

I'd like to create a new new table consisting of patients that have diagnosis codes 299 and 233.

The code tried so far has been

Select *
  From mytable 
 where diagnosis_id = 299 AND diagnosis_id=233

This hasn't worked -

I've also tried

Select *
  From mytable 
 where diagnosis_id = 299 
INTERSECT
Select *
From mytable 
where diagnosis_id= 233

This hasn't worked either.

like image 228
willepi Avatar asked Dec 24 '22 18:12

willepi


2 Answers

select  Subject_ID from (
     Select Distinct Subject_ID, Diagnosis_ID
       From
       Table_1
       Where Diagnosis_ID=299 or Diagnosis_ID=288
)
Group By Subject_ID
Having count(Subject_ID)>=2
like image 157
SAEED REZAEI Avatar answered Jan 04 '23 23:01

SAEED REZAEI


Think group by and having:

Select patient_id
From mytable
where diagnosis_id in (299, 233)
group by patient_id
having count(*) = 2;

Note: If your table can have duplicates, then use count(distinct diagnosis_id) = 2.

like image 43
Gordon Linoff Avatar answered Jan 04 '23 22:01

Gordon Linoff