2016-08-03 85 views
0

我的醫院數據庫中有四張表。我需要顯示所有患者的姓名以及每位患者的姓名,他們不止一次訪問過的醫生的姓名以及每位醫生的訪問次數。如果患者未訪問過任何醫生,或者不是多次訪問任何醫生,管理層不希望將其列入清單中。編寫一個查詢來爲管理檢索這些信息。加入和分組問題

Select * from Medical_History; 
Select * from Physician; 
Select * from Appointment; 
Select * from Patient; 

enter image description here

我已經加入查詢以及一組查詢,但我不知道如何將它們結合起來。因爲我正在分組錯誤。因爲我需要顯示病人對醫生的訪問次數,而且必須超過一次。所以需要幫助。這裏的加入和組子句:

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; 
+1

請檢查此鏈接以瞭解如何改善問題..https://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/ – TheGameiswar

+0

您可以按patientid,patientname,phyician,physicianname進行分組 - 在您的選擇中,您需要將count(*)計爲'numberOfTimesPatentSawConsultant',並且您需要執行Having Count(*)> 1 – Cato

回答

1

你可以先用GROUP BYHAVING得到患者和醫生協會,然後用他們的每一個主表的加盟讓他們的名字。

事情是這樣的:

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; 
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記錄。