An aggregated expression containing an outer reference must be contained in either the select list or a subquery of the HAVING clause of the query whose FROM clause contains the table containing the column being aggregated.