如何在同一个表中选择具有特定行值的参与者ID,这些行值来自另一个模式中的查找列表?

ef1yzkbh  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(422)

我想从一个表中选择参与者,该表在b列中同时有癌症和糖尿病的诊断
例如:

ParticipantID Diagnosis
1234          Cancer 
1234          Diabetes
4567          Cancer
4567          Lung Disease
8910          Stroke
1256          Lung Disease
3489          Chron's Disease

如何编写一个查询,允许我选择具有两个(或更多)特定诊断的参与者,例如,我只希望看到同时患有癌症和糖尿病的参与者(在上面的示例中,参与者id为1234)
我试着做一个简单的select语句:

SELECT diagnosisifknown.participantid
diagnosisifknown.diagnsis
diagnosisifknown.date
FROM
diagnosisifknown
where diagnosis ="1" and "10";

(查找表中这些诊断的值)
我想要这样的输出:

1234   Cancer
1234   Diabetes
vbkedwbf

vbkedwbf1#

聚合提供了一个简单的选项:

SELECT ParticipantID
FROM yourTable
GROUP BY ParticipantID
HAVING MIN(Diagnosis) <> MAX(Diagnosis);

您也可以在这里使用exists逻辑:

SELECT t1.ParticipantID
FROM yourTable t1
WHERE EXISTS (SELECT 1 FROM yourTable t2
              WHERE t2.ParticipantID = t1.ParticipantID AND t2.Diagnosis <> t1.Diagnosis);
gajydyqb

gajydyqb2#

你可以用cte做,这是演示。

with cte as
(
  select
    ParticipantID
  from myTable
  where Diagnosis in ('Cancer', 'Diabetes')
  group by
      ParticipantID
  having count(ParticipantID) > 1
)

select
    c.ParticipantID,
    m.Diagnosis
from cte c
join myTable m
on c.ParticipantID = m.ParticipantID

输出:

| participantid | diagnosis |
| ------------- | --------- |
| 1234          | Cancer    |
| 1234          | Diabetes  |
bkhjykvo

bkhjykvo3#

如果需要参与者,可以使用:

SELECT d.participantid
FROM diagnosisifknown d
WHERE diagnosis IN ('Cancer', 'Diabetes')
GROUP BY d.participantid
HAVING COUNT(*) = 2;

如果你想要原始行,我建议你 EXISTS :

select d.*
from diagnosisifknown d
where exists (select 1
              from diagnosisifknown d2
              where d2.participantid = d.participantid and d2.diagnosis = 'Cancer'
             ) and
      exists (select 1
              from diagnosisifknown d2
              where d2.participantid = d.participantid and d2.diagnosis = 'Diabetes'
             ) ;

相关问题