协助SQL查询

时间:2015-12-12 12:45:00

标签: sql

假设我们有2个表:

  1. Patients(身份证,姓名)
  2. Patients_Treatments(PatientID,treatment_code)
  3. 我希望查询能够检索至少接受id='999999999'

    患者治疗的所有患者的所有患者

    我尝试了很多组合,没有任何效果,我得到的是至少有一种'9999999999'治疗方法的患者。

2 个答案:

答案 0 :(得分:2)

一种方法在having子句中使用自连接和比较:

select pt2.patientId
from patient_treatments pt join
     patient_treatments pt2
     on pt.treatment_code = pt2.treatment_code and pt.patientid <> pt2.patientid
where pt.id = '999999999'
group by pt2.patientId
having count(pt2.treatment_code) = (select count(*) from patient_treatments pt where pt.id = '999999999');

注意:此版本假定Patient_Treatments中没有重复项。

如果您在数据中有重复项,则可以使用count(distinct)

having count(distinct pt2.treatment_code) = (select count(distinct pt.treatment_code) from patient_treatments pt where pt.id = '999999999');

答案 1 :(得分:0)

这个想法是

(1)选择属于患者的治疗代码“999999999”

(2)仅选择治疗代码与属于患者的治疗代码之一匹配的治疗记录“999999999”

(3)通过patient_id对这些进行分组

(4)使用HAVING语句和COUNT(DISTINCT)仅选择与患者“999999999”具有相同数量的不同治疗代码的患者ID。

select pt.Patient_ID,count(distinct pt.treatment_code)
from
Patient_treatments pt
inner join
(select distinct treatment_code
 from 
 Patient_treatments pt
 where pt.Patient_ID="999999999"
 )t1
 on t1.treatment_code=pt.treatment_code
 where pt.Patient_ID<>"999999999"
 group by pt.Patient_ID
 having count(distinct pt.treatment_code)=
 (select count(distinct treatment_code) 
  from 
  Patient_treatments pt
  where pt.Patient_ID="999999999"
  );

使用以下模式,仅选择患者1: -

  Create table Patient_Treatments
  (
    Patient_ID varchar(10),
    Treatment_code varchar(10)
    );


   Insert into Patient_Treatments
    values
    ("1","abc"),
    ("1","def"),
    ("1","def"),
    ("1","ghi"),
    ("2","abc"),
    ("2","def"),
    ("2","def"),
    ("3","ghi"),
    ("999999999","abc"),
    ("999999999","def"),
    ("999999999","ghi"),
    ("999999999","ghi")

http://sqlfiddle.com/#!9/03a84b