【发布时间】:2021-12-30 21:33:17
【问题描述】:
我有 3 张表 Doctor、Patient、DoctorPatient。医生有字段 ID、姓名、电话。患者有字段 ID、姓名、电话、年龄、性别。 DoctorPatient 包含 DoctorID 和 PatienId,这是 Doctor 和 Patient 表之间的链接。如何找到所有患者年龄小于 30 岁的医生?
表之间有关系
【问题讨论】:
我有 3 张表 Doctor、Patient、DoctorPatient。医生有字段 ID、姓名、电话。患者有字段 ID、姓名、电话、年龄、性别。 DoctorPatient 包含 DoctorID 和 PatienId,这是 Doctor 和 Patient 表之间的链接。如何找到所有患者年龄小于 30 岁的医生?
表之间有关系
【问题讨论】:
如果按医生分组,则患者总数必须与 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
【讨论】:
age >= 30。它还将返回没有病人的医生。那些也没有任何 30 岁以下的患者。