SQL Server 2005 One query to calculate two tables

I am starting to work in SQL Server

I have three tables in a hospital database

  • Patientfiles
  • Other services
  • PatientDeposit

Two queries to display my result

  • Request number one. Show PatientFilesID, TotalOtherServices

    SELECT pf.ID AS PatientFileID, SUM(os.Quantum * os.Price) AS TotalOtherServices
    FROM PatientsFiles pf INNER JOIN OtherServices os ON pf.ID = os.Patient_File_ID 
    WHERE pf.ID = '14'
    GROUP BY pf.ID
    

This is the true result.

    PatientFileID  | TotalOtherServices
        14                194.00
  • Request number two. Show PatientFilesID, TotalPatientDeposit

    SELECT pd.Patient_File_ID AS PatientFileID, SUM(pd.Deposit) AS TotalPatientDeposit
    FROM PatientsDeposits pd
    WHERE pd.Patient_File_ID = '14'
    GROUP BY pd.Patient_File_ID
    

This is the true result.

    PatientFileID | TotalPatientDeposit
        14               450.00
  • My very tired mix two requests

    SELECT pf.ID AS PatientFileID, SUM(os.Quantum * os.Price) AS TotalOtherServices, 
    SUM(pd.Deposit) AS TotalPatientDeposit
    FROM PatientsFiles pf
    INNER JOIN OtherServices os ON pf.ID = os.Patient_File_ID  
    INNER JOIN PatientsDeposits pd ON pf.ID = pd.Patient_File_ID
    WHERE pf.ID = '14'
    GROUP BY pf.ID
    

This is the wrong result.

    PatientFileID  | TotalOtherServices | TotalPatientDeposit
         14                  582.00         1350.00

Thanks for helping me in advance.

+3
source share
2 answers
Select pf.ID as PatientFileID,
    os.TotalOtherServices,
    pd.TotalDeposit
From PatientFiles pf
    Left Join
 (Select Patient_File_ID as PatientfileID, SUM(os.Quantum * os.Price) AS TotalOtherServices
  From OtherServices Group By Patient_File_ID) os on pf.PatientFileID = os.PatientFileID
    Left Join
 (Select Patient_File_ID AS PatientFileID, SUM(Deposit) AS TotalPatientDeposit
  From PatientsDeposits Group By Patient_File_ID) pd on pf.PatientFileID = pd.PatientFileID
+1
source

With a quick glance, it looks like the values ​​are 3 times larger than expected.
(194 * 3 = 582, 450 * 3 = 1350).

, INNER JOIN.

SELECT pf.ID AS PatientFileID, 
SUM(pd.Deposit) AS TotalPatientDeposit
FROM PatientsFiles pf INNER JOIN PatientsDeposits pd
ON pf.ID = pd.Patient_File_ID
WHERE pd.Patient_File_ID = '14'
GROUP BY pd.Patient_File_ID

, , .

0

Source: https://habr.com/ru/post/1756683/


All Articles