我正在编写我认为对于我的医生客户来说相对简单的Access DB,他的实践非常少。我在报告患者的平衡方面遇到了麻烦。
我有3张桌子:
Patients (id, [First Name], [Last Name], {other cols})
Treatments (id, Fee, Patient_id, {other cols})
Payments (id, Amount, Patient_id, {other cols})
我想要一个查询,只是告诉我治疗费用总额,支付总金额和当前余额。我写了以下内容......
Select
Patients.[Last Name],
Patients.[First Name],
SUM(select SUM(Treatments.Fee) from Treatments Where Treatments.Patient=@PatientID)
AS CHARGES,
SUM(select SUM(PAYMENTS.AMOUNT) from PAYMENTS Where PAYMENTS.Patient=@PatientID)
AS PAYMENTS,
SUM(
(select SUM(Treatments.Fee) from Treatments Where Treatments.Patient=@PatientID)
- (select SUM(PAYMENTS.AMOUNT) from PAYMENTS Where PAYMENTS.Patient=@PatientID)
)
as Balance
FROM Patients,Treatments,PAYMENTS
WHERE Patients.ID = @PatientID
GROUP BY Patients.[Last Name],Patients.[First Name]
费用和付款列工作正常,但我给出的余额很奇怪。以下是基于:
我希望: 费用= 280美元,付款= 100美元,余额= 180美元
但我明白了: 费用= 280美元,付款= 100美元,余额= 2,700美元
答案 0 :(得分:1)
Select
Patients.[Last Name],
Patients.[First Name],
SUM( treatments.Fee)
AS CHARGES,
SUM(PAYMENTS.AMOUNT)
AS PAYMENTS,
SUM(Treatments.Fee)
- SUM(PAYMENTS.AMOUNT)
as Balance
FROM Patients a join Treatments b on a.id=b.patientid join PAYMENTS c on a.id=c.patientid
WHERE Patients.ID = @PatientID
GROUP BY Patients.[Last Name],Patients.[First Name]
答案 1 :(得分:1)
使用此FROM子句:
FROM Patients,Treatments,PAYMENTS
您正在创建笛卡尔积。 这意味着您的余额计算将乘以每个表中的记录数(患者为1,治疗为5,付款为3):
在您的子查询中进行计算时,您的FROM子句中不需要处理和付款。 请改用此语句:
Select
Patients.[Last Name],
Patients.[First Name],
SUM(select SUM(Treatments.Fee) from Treatments Where Treatments.Patient=@PatientID)
AS CHARGES,
SUM(select SUM(PAYMENTS.AMOUNT) from PAYMENTS Where PAYMENTS.Patient=@PatientID)
AS PAYMENTS,
SUM(
(select SUM(Treatments.Fee) from Treatments Where Treatments.Patient=@PatientID)
- (select SUM(PAYMENTS.AMOUNT) from PAYMENTS Where PAYMENTS.Patient=@PatientID)
)
as Balance
FROM Patients
WHERE Patients.ID = @PatientID
GROUP BY Patients.[Last Name],Patients.[First Name]