Home > Database > Mysql Tutorial > How to Correctly Aggregate SUM Values Across Multiple Database Tables?

How to Correctly Aggregate SUM Values Across Multiple Database Tables?

Susan Sarandon
Release: 2024-12-29 05:45:11
Original
955 people have browsed it

How to Correctly Aggregate SUM Values Across Multiple Database Tables?

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
Copy after login

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]
Copy after login

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]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template