SQL Server Error 1015: Aggregate Cannot Appear in an ON
In this article
SQL Server Error 1015 occurs because you are attempting to use an aggregate function—such as SUM(), AVG(), MAX(), MIN(), or COUNT()—directly within the ON clause of a JOIN. To fix this, you must move the aggregation into a Common Table Expression (CTE) or a subquery, calculate the aggregate value first, and then join the resulting set to your main table.
What You'll Need
- Access to SQL Server Management Studio (SSMS) or another T-SQL compatible editor.
- An existing database with tables containing the data you wish to aggregate and join.
- Basic understanding of JOIN operations and the GROUP BY clause.
Step-by-Step
- Identify the offending line: Locate the JOIN statement in your query where you have placed an aggregate function. For example, if you have a line like
JOIN Orders ON Customers.CustomerID = MAX(Orders.CustomerID), this is the source of Error 1015. SQL Server processes JOIN conditions before it performs aggregations, making it logically impossible to filter a join based on a sum or average that hasn't been calculated yet. - Isolate the aggregation logic: Determine exactly which table needs to be aggregated and which columns are required for the grouping. If you need the total order value per customer, you need the
CustomerIDand theSUM(OrderValue)from the Orders table. - Create a Common Table Expression (CTE): The cleanest way to resolve this is to use a CTE. Start your query with the
WITHkeyword. Inside the CTE, write a SELECT statement that performs the aggregation and includes a GROUP BY clause.
Example:
WITH OrderTotals AS (
SELECT CustomerID, SUM(OrderAmount) as TotalSpent
FROM Orders
GROUP BY CustomerID
) - Join the CTE to your main table: Now that the aggregation is performed in a temporary result set (the CTE), you can join your main table to this set using a standard column comparison. The aggregate value is now treated as a regular column.
Example:
SELECT Customers.CustomerName, OrderTotals.TotalSpent
FROM Customers
JOIN OrderTotals ON Customers.CustomerID = OrderTotals.CustomerID - Alternative: Use a Derived Table: If you prefer not to use a CTE, you can place the aggregation logic inside a subquery within the FROM clause. This is functionally identical to a CTE but can be more compact for very simple queries.
Example:
SELECT C.CustomerName, OT.TotalSpent
FROM Customers C
JOIN (SELECT CustomerID, SUM(OrderAmount) as TotalSpent FROM Orders GROUP BY CustomerID) OT
ON C.CustomerID = OT.CustomerID - Apply filters to the aggregate result: If your original goal was to join only records that met a certain aggregate threshold (e.g., only customers who spent over $1,000), do not put this in the ON clause. Instead, use a WHERE clause after the join or a HAVING clause inside the CTE/subquery.
- Verify the results: Run the query and compare the output against your expected data. Ensure that the grain of the data (the number of rows returned) is correct and that the aggregation is calculating across the intended groups.
Common Mistakes
One of the most frequent mistakes is attempting to move the aggregate function from the ON clause to the WHERE clause without using a subquery. For instance, writing WHERE Customers.ID = SUM(Orders.ID) will trigger a different error (Error 8120), as aggregates cannot appear in the WHERE clause either. Remember that aggregates require a GROUP BY context.
Another common error is forgetting to include the joining key in the SELECT list of the subquery or CTE. If you calculate the SUM of sales but forget to SELECT the CustomerID in the subquery, the outer JOIN has no column to link to, resulting in a "column not found" error.
Users often confuse the ON clause with the HAVING clause. The ON clause defines how tables are linked; the HAVING clause filters the results of an aggregation. You cannot use HAVING to perform the join itself; you must aggregate first, then join, then filter.
Finally, some developers try to use Window Functions (like SUM() OVER()) inside the ON clause. While Window Functions are powerful, they are processed after the JOIN and WHERE clauses, meaning they are also prohibited in the ON clause of a JOIN.
Tips
For better performance, perform the aggregation on the smallest possible dataset. If you have a massive Orders table but only need data for the current year, put a WHERE clause inside your CTE to filter the dates before the GROUP BY happens. This reduces the amount of data SQL Server has to sort and aggregate in memory.
Use aliases for your subqueries and CTEs. When you create a derived table, SQL Server requires it to have a name (e.g., ) AS AggregatedData). Using descriptive aliases makes your code much easier to read and maintain for other developers.
If you find yourself creating many CTEs for different aggregates in one query, consider if a temporary table (#TempTable) might be more efficient. Temporary tables allow you to add indexes to the aggregated columns, which can significantly speed up the final join if the dataset is large.
Always check the execution plan in SSMS (Ctrl+L) when moving from an invalid ON clause to a CTE. Ensure that the optimizer is choosing an efficient join type (like a Hash Match or Merge Join) rather than a Nested Loop that could slow down your query.
Troubleshooting
If you have moved the aggregate to a CTE but are still seeing unexpected results, check for NULL values in your joining columns. Aggregates like SUM() ignore NULLs, but if your joining key (e.g., CustomerID) is NULL, those rows will be dropped from an INNER JOIN. Use a LEFT JOIN if you need to keep all records from the primary table regardless of whether they have aggregated data.
If the query is running extremely slowly after the fix, verify that the columns used in the GROUP BY clause of your subquery are indexed. Without an index on the grouping column, SQL Server must perform a full table scan and a costly sort operation to calculate the aggregates.
If you receive an error stating that a column is "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause," it means you have included a column in your CTE's SELECT list that isn't being aggregated. Every non-aggregated column in your subquery must be listed in the GROUP BY clause.
If you are getting duplicate rows in your final output, check the grain of your aggregation. Ensure that the GROUP BY clause in your CTE produces exactly one row per joining key. If you group by both CustomerID and OrderDate, but join only on CustomerID, you will get multiple rows per customer in your final result.
Frequently Asked Questions
Why can't I just use a subquery in the ON clause?
While you can technically use a scalar subquery (a query that returns a single value) in some parts of a statement, SQL Server's join engine is designed to evaluate join predicates against row-level values. Aggregates represent a set of rows, creating a logical conflict in the order of operations.
Does using a CTE slow down the query compared to a JOIN?
A CTE is generally a syntactic sugar for a derived table; the SQL Server optimizer typically treats them the same way. The performance impact comes from the aggregation itself (the GROUP BY), not from the use of a CTE versus a subquery.
Can I use MAX() or MIN() in the ON clause if it's a constant?
No. Regardless of whether the result is a single constant or a varying value, the syntax rules of T-SQL prohibit aggregate functions within the ON clause of a JOIN.
What is the difference between using HAVING and moving the aggregate to a CTE?
HAVING filters rows after they have been grouped and aggregated. Moving the logic to a CTE allows you to create a virtual table of aggregated values that you can then join to other tables, which is necessary when the aggregate value is required for the join condition itself.
Is there a way to do this without a CTE or subquery?
Not if you need the aggregate to determine which rows are joined. You must first reduce the many-to-one relationship into a one-to-one relationship via aggregation before the JOIN can be executed.