将2个查询与所涉及的总和相结合

时间:2015-07-11 02:48:54

标签: ms-access

我有两个类似的查询,看起来都是这样的,只有表在第二个查询中从治疗转为患者:

SELECT Treatment.Phys_ID AS Phys_ID, Physician.FName, Physician.LName, Sum(Treatment.Charge) AS TotCharge 
FROM Physician 
INNER JOIN Treatment ON Physician.Phys_ID = Treatment.Phys_ID
GROUP BY Treatment.Phys_ID, Physician.FName, Physician.LName;

两者的输出是:

Phys_ID___FName___LName____TotCharge

合并后,我需要添加2个查询的TotCharge列来获取实际的TotCharge。但是,当我UNION ALL这两个查询时,表只是堆叠在一起,而UNION只是重新排列两个表,所以相同的Phys_ID彼此相邻。如何让2个查询'TotCharges加起来?

1 个答案:

答案 0 :(得分:1)

您可以使用子查询在医生级别添加费用:

SELECT Physician.Phys_ID AS Phys_ID, Physician.FName, Physician.LName, 

  (SELECT Nz(Sum(Treatment.Charge)) 
   FROM Treatment WHERE Treatment.Phys_ID = Physician.Phys_ID) +

  (SELECT Nz(Sum(Patient.Charge))
   FROM Patient WHERE Patient.Phys_ID = Physician.Phys_ID) As Total Charge

FROM Physician;

或者,您可以使用DSum(严格来说是MS Access功能而不是ANSI SQL)。

SELECT Physician.Phys_ID AS Phys_ID, Physician.FName, Physician.LName, 

   Nz(DSum("Charge", "Treatment", "Phys_ID =" &  Physician.Phys_ID)) +

   Nz(DSum("Charge", "Patient", "Phys_ID =" & Physician.Phys_ID)) As Total Charge

FROM Physician;