Spetsnaz Beaver
Spetsnaz Beaver

Reputation: 13

Combine 2 queries with sum involved

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?

Upvotes: 0

Views: 58

Answers (1)

Parfait
Parfait

Reputation: 107642

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;

Upvotes: 1

Related Questions