Combining Data from Multiple Tables for Summation: Addressing Incorrect Results
In your SQL query, you aim to retrieve a table consisting of three columns: "PROJECT," "SUM_AP," and "SUM_INV." However, you have encountered incorrect results due to grouping in the aggregation process.
Cause of Incorrect Results:
The "GROUP BY" clause in your query combines values based on the "AP.[PROJECT]" column. This aggregation process essentially sums up duplicate "Value" entries, leading to inflated results.
Solution: Using Sub-Select Queries
To address this issue, we can modify your query using sub-select queries:
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]
Explanation:
This revised query ensures that only distinct "PROJECT" values are grouped, and the sums are calculated correctly, providing the intended result.
The above is the detailed content of Why are my SQL sum calculations incorrect when combining multiple tables, and how can I fix them using subqueries?. For more information, please follow other related articles on the PHP Chinese website!