SQL - 多个条件where子句相同的列

时间:2017-04-22 19:14:13

标签: sql

我有一个看起来像这样的

的数据集
Subject_ID   Diagnosis_ID  
001          299
001          288
001          233
001          299
002          299
002          233
003          238
004          299
004          233

我想创建一个由患者组成的新表 诊断代码299和233.

到目前为止尝试的代码已经

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

这还没有用 -

我也试过

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

这也没有奏效。

5 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

思考group byhaving

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

注意:如果您的表格可能有重复项,请使用count(distinct diagnosis_id) = 2

答案 2 :(得分:1)

检查: -

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

感谢: - )

答案 3 :(得分:0)

你可以使用IN()....

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

答案 4 :(得分:0)

简单,您可以使用:

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