[英]SQL Server 2005 One query to calculation two table
我是SQL Server的初学者
我在数据库医院有三张桌子
两个查询显示我的结果
查询第一。 显示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
这是真实的结果
PatientFileID | TotalOtherServices
14 194.00
查询号码二。 显示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
这是真实的结果
PatientFileID | TotalPatientDeposit
14 450.00
我非常厌倦混合两个查询
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
这是错误的结果
PatientFileID | TotalOtherServices | TotalPatientDeposit
14 582.00 1350.00
谢谢你提前帮助我
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
快速浏览一下,看起来价值比预期大3倍。
(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
我知道这不是答案,而是更多应该检查的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.