SQL Joins and Subqueries/Join to an aggregated subquery

Pre-aggregate a table and join the result.

Section: Join Conditions and Filters

Join to an aggregated subquery

sql
sql
SELECT c.customer_id, x.total_spent
FROM customers c
JOIN (
  SELECT customer_id, SUM(amount) AS total_spent
  FROM orders
  GROUP BY customer_id
) x ON x.customer_id = c.customer_id;
Explanation

This pattern keeps the outer query simpler when joining summarized data.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Join Conditions and Filters
Join with additional predicate
Add extra conditions to the join itself.
OpenIn sheetsqlsame section
Find missing related rows
Use LEFT JOIN plus NULL filtering to find unmatched rows.
OpenIn sheetsqlsame section
Use a subquery in WHERE
Filter rows based on results from another query.
OpenIn sheetsql1 tag match
Filter with EXISTS
Return rows when a related row exists.
OpenIn sheetsql1 tag match
Scalar subquery
Return a single value from a nested query.
OpenIn sheetsql1 tag match
Filter with NOT EXISTS
Return rows with no related matches.
OpenIn sheetsql1 tag match