【问题标题】:SQL. Find doctors' names who have all patients with age less than 30SQL。查找所有患者年龄小于 30 岁的医生姓名
【发布时间】:2021-12-30 21:33:17
【问题描述】:

我有 3 张表 Doctor、Patient、DoctorPatient。医生有字段 ID、姓名、电话。患者有字段 ID、姓名、电话、年龄、性别。 DoctorPatient 包含 DoctorID 和 PatienId,这是 Doctor 和 Patient 表之间的链接。如何找到所有患者年龄小于 30 岁的医生?

表之间有关系

【问题讨论】:

    标签: sql ms-access


    【解决方案1】:

    如果按医生分组,则患者总数必须与 30 岁以下的患者总数相同。

    SELECT Doctor.name
    , COUNT(IIF(Patient.age < 30, Patient.ID, null)) AS TotalPatientsUnder30
    , COUNT(Patient.ID) AS TotalPatients
    FROM Doctor 
    JOIN DoctorPatient AS dopa ON dopa.DoctorID = Doctor.ID
    JOIN Patient ON Patient.ID = dopa.PatientID
    GROUP BY Doctor.ID, Doctor.name
    HAVING COUNT(Patient.ID) = COUNT(IIF(Patient.age < 30, Patient.ID, null))
       AND COUNT(Patient.ID) > 0
    

    【讨论】:

    • 有我的解决方案: SELECT x.Name FROM Doctor AS x WHERE x.DoctorID NOT IN ( SELECT DISTINCT DoctorPatient.DoctorID FROM Patient INNER JOIN DoctorPatient ON Patient.ID = DoctorPatient.PatientID WHERE Patient.age > 30 );
    • 否定应该起作用。但它应该是age &gt;= 30。它还将返回没有病人的医生。那些也没有任何 30 岁以下的患者。
    【解决方案2】:

    给出sql:

    SELECT Doctors.DoctorName, Max(Patients.age) AS MaxOfage
    FROM Patients INNER JOIN (Doctors INNER JOIN DoctorPatient ON Doctors.ID = DoctorPatient.DoctorID) ON Patients.ID = DoctorPatient.PatientID
    GROUP BY Doctors.DoctorName
    HAVING (((Max(Patients.age))<30));
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多