使用减法访问SQL SUM

时间:2018-03-28 18:47:10

标签: sql tsql ms-access ms-access-2016

我正在编写我认为对于我的医生客户来说相对简单的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]

费用和付款列工作正常,但我给出的余额很奇怪。以下是基于:

  1. 该患者的5个治疗项目,金额为50,25,35,45,125(280)。
  2. 3笔付款条目,金额为15,60,25(100)。
  3. 我希望: 费用= 280美元,付款= 100美元,余额= 180美元

    但我明白了: 费用= 280美元,付款= 100美元,余额= 2,700美元

2 个答案:

答案 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):

  • 15 *费用总额 - 15 *付款总额= 15 * 280-15 * 100 = 4200-1500 = 2700

在您的子查询中进行计算时,您的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]