我的医院数据库中有四张桌子。我需要显示所有患者的姓名,并为每位患者显示他们不止一次访问过的医生的姓名,以及每位医生的访问次数。如果患者没有去过任何医生,或者没有多次访问任何医生,管理层不希望在列表中看到他们。编写一个查询,以便为管理层检索此信息。
Select * from Medical_History;
Select * from Physician;
Select * from Appointment;
Select * from Patient;
我已经进行了连接查询以及组查询,但我不知道如何组合它们。因为我正在分组错误。因为我需要显示患者到医生的就诊次数,并且必须不止一次。所以需要帮助。这是加入和组子句:
Select Patient_First_Name, Patient_Last_Name,Physician_First_Name,Physician_Last_Name
from Patient Join Medical_History on Patient.Patient_ID=Medical_History.Patient_ID
Join Physician on Medical_History.Physician_ID=Physician.Physician_ID;
select Physician_ID, count(Patient_ID)
from Medical_History
Group by Physician_ID, Patient_ID;
答案 0 :(得分:1)
您可以先将GROUP BY
与HAVING
一起使用,以获取患者和医生的关联,然后加入每个主表以获取其姓名。
这样的事情:
SELECT
Patient_First_Name,
Patient_Last_Name,
Physician_First_Name,
Physician_Last_Name,
TotalVisits
FROM Patient P
INNER JOIN
(
SELECT Patient_ID, Physician_ID, COUNT(*) as TotalVisits
FROM Medical_History
GROUP BY Physician_ID, Patient_ID
HAVING COUNT(*) >= 2
) PP ON P.Patient_ID = PP.Patient_ID
INNER JOIN Physician PH ON PH.Physician_ID = PP.Physician_ID;
答案 1 :(得分:0)
我会CROSS APPLY
计算每个Patient
记录,如下所示:
SELECT Patient_First_Name, Patient_Last_Name,Physician_First_Name,Physician_Last_Name
FROM Patient
CROSS APPLY (SELECT Physician_First_Name,Physician_Last_Name,COUNT(*) TotalVisits
FROM Medical_History
JOIN Physician on Medical_History.Physician_ID=Physician.Physician_ID
WHERE Medical_History.Patient_ID=Patient.Patient_ID
GROUP BY Physician_First_Name,Physician_Last_Name
HAVING COUNT(*)>1) T
内部查询选择与Patient
具有多个关联的记录。