Course contentsShow
← Databases & SQL
Lesson 314 of 1,9534. Advanced Data AggregationFree lesson

Aggregating Data from Multiple Sources

Perform cross-table aggregation while maintaining group integrity.

Aggregating Data Across Tables

In this lesson, you will learn how to perform cross-table aggregations while ensuring your data groupings remain accurate and integrity is preserved.

When you need to pull metrics from different tables—for example, calculating the total Sales from one table and total Support_Tickets from another—it is tempting to join the tables first and then aggregate. However, if a single user has multiple rows in both tables, a simple JOIN will create a "Cartesian product" effect. This causes your sums to be inflated because the rows are duplicated before the math happens.

The Strategy: Aggregate First, Join Second

To maintain group integrity, the safest pattern is to perform your aggregations in subqueries or Common Table Expressions (CTEs) before combining them. This ensures that each source is summarized to the unique entity level (e.g., user_id) before they are merged.

Consider this scenario where we want to summarize activity per user:

WITH UserSales AS (
    SELECT user_id, SUM(amount) as total_spent
    FROM orders
    GROUP BY user_id
),
UserTickets AS (
    SELECT user_id, COUNT(ticket_id) as total_tickets
    FROM support_tickets
    GROUP BY user_id
)
SELECT 
    u.user_id,
    s.total_spent,
    t.total_tickets
FROM users u
LEFT JOIN UserSales s ON u.user_id = s.user_id
LEFT JOIN UserTickets t ON u.user_id = t.user_id;

Why this matters

By aggregating the orders and support_tickets independently, we guarantee that the SUM and COUNT logic are applied to the raw source data only once. If you had joined orders and support_tickets directly, a user with 5 orders and 5 tickets would suddenly appear to have 25 rows, leading to incorrect calculations.

By keeping the aggregation logic isolated in the CTEs, you treat each data source as a distinct, summarized entity. This "Aggregate-Before-Joining" approach is the most reliable way to avoid the data duplication traps that plague cross-table reporting.

Key Takeaway: Always aggregate data in isolated steps before joining to prevent row duplication and ensure the mathematical accuracy of your cross-source metrics.