Combine 2 queries with sum involved

浪子不回头ぞ 提交于 2019-12-31 05:26:09

问题


I have 2 similar queries that both look like this with only the table being switched from Treatment to Patient in the second query:

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;

The output of both is:

Phys_ID___FName___LName____TotCharge

When combined, I need to add the 2 queries' columns of TotCharge to get the actual TotCharge. However, when I UNION ALL these 2 queries the tables just stack on top of each other and UNION just rearanges both tables so identical Phys_IDs are next to each other. How can I make the 2 queries' TotCharges add up?


回答1:


You can use subqueries to add the charges at the Physician level:

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;

Alternatively, you can use DSum (strictly an MS Access function and not 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;


来源:https://stackoverflow.com/questions/31350299/cant-figure-out-how-to-perform-this-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!