简体   繁体   中英

SQL - Multiple conditions where clause the same column

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.

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

you can use IN()... .

  SELECT * FROM TABLE
  WHERE diagnosis_id IN(233, 299);

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 .

Check this:-

Select subject_id 
from
(
Select distinct subject_id, diagnosis_id
from
mytable
where diagnosis_id in ('299','233')
) a
group by subject_id
having count(*)=2

Thanks:-)

Simple, you can use this :

Select *
  From mytable 
 where (diagnosis_id = 299 or diagnosis_id=233)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM