繁体   English   中英

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

[英]SQL how to select participant IDs with specific row values in same table, where those row values are from a lookup list in another schema?

我想从一个表中 select 参与者在 B 列中同时诊断为癌症和糖尿病

例如:

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

如何编写一个查询,允许我查询具有两个(或多个)特定诊断的 select 参与者,例如,我只想查看同时患有癌症和糖尿病的参与者? (在上述示例中,参与者 ID 为 1234)

我尝试做一个简单的 select 语句:

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

(查找表中这些诊断的值)

我想要一个像这样的 output :

1234   Cancer
1234   Diabetes

聚合提供了一种简单的选择:

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

你也可以在这里使用存在逻辑:

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

你可以用 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

output:

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

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

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'
             ) ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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