Database Aggregation across Multiple Tables: Correcting Sum Calculations
When dealing with multiple tables in a database, aggregation functions like SUM require careful handling to ensure accurate results. This is exemplified by a query attempting to calculate the sum of values from two tables, AP and INV, both having columns [PROJECT] and [Value]. The desired output should resemble:
PROJECT | SUM_AP | SUM_INV
However, the provided query exhibited incorrect results due to an error in summation:
SELECT AP.[PROJECT], SUM(AP.Value) AS SUM_AP, SUM(INV.Value) AS SUM_INV FROM AP INNER JOIN INV ON (AP.[PROJECT] =INV.[PROJECT]) WHERE AP.[PROJECT] = 'XXXXX' GROUP BY AP.[PROJECT]
The issue lies in the grouping of values. The GROUP BY clause combines duplicate values, which leads to incorrect sums.
To rectify this, sub-selects can be employed:
SELECT AP1.[PROJECT], (SELECT SUM(AP2.Value) FROM AP AS AP2 WHERE AP2.PROJECT = AP1.PROJECT) AS SUM_AP, (SELECT SUM(INV2.Value) FROM INV AS INV2 WHERE INV2.PROJECT = AP1.PROJECT) AS SUM_INV FROM AP AS AP1 INNER JOIN INV AS INV1 ON (AP1.[PROJECT] =INV1.[PROJECT]) WHERE AP1.[PROJECT] = 'XXXXX' GROUP BY AP1.[PROJECT]
This approach calculates the sums separately for each [PROJECT] using sub-selects, resulting in accurate aggregation.
The above is the detailed content of How to Correctly Aggregate SUM Values Across Multiple Database Tables?. For more information, please follow other related articles on the PHP Chinese website!