              raise FieldError("Joined field references are not permitted in this query")
          if name in self.annotations:
              if summarize:
                  return Ref(name, self.annotation_select[name])
              else:
                  return self.annotation_select[name]
          else:
              field_list = name.split(LOOKUP_SEP)
              field, sources, opts, join_list, path = self.setup_joins(
 
</s> remove                 if sql not in seen:
 </s> add                 if sql not in seen or col_params: </s> remove                     self.compile(col)
 </s> add                     sql, col_params = self.compile(col) </s> remove             for alias, annotation in inner_query.annotation_select.items():
                if annotation.is_summary:
                    # The annotation is already referring the subquery alias, so we
                    # just need to move the annotation to the outer query.
                    outer_query.annotations[alias] = annotation.relabeled_clone(relabels)
 </s> add             col_cnt = 0
            for alias, expression in inner_query.annotation_select.items():
                if expression.is_summary:
                    expression, col_cnt = inner_query.rewrite_cols(expression, col_cnt)
                    outer_query.annotations[alias] = expression.relabeled_clone(relabels)
                # Summarize currently means we are doing an aggregate() query
                # which is executed as a wrapped subquery if any of the
                # aggregate() elements reference an existing annotation. In
                # that case we need to return a Ref to the subquery's annotation.
              raise FieldError("Joined field references are not permitted in this query")
          if name in self.annotations:
              if summarize:
                # Summarize currently means we are doing an aggregate() query
                # which is executed as a wrapped subquery if any of the
                # aggregate() elements reference an existing annotation. In
                # that case we need to return a Ref to the subquery's annotation.
                  return Ref(name, self.annotation_select[name])
              else:
                  return self.annotation_select[name]
          else:
              field_list = name.split(LOOKUP_SEP)
              field, sources, opts, join_list, path = self.setup_joins(
keep keep add keep keep keep keep keep keep
 Fixed #23877 -- aggregation's subquery missed target col

Aggregation over subquery produced syntactically incorrect queries in
some cases as Django didn't ensure that source expressions of the
aggregation were present in the subquery. 
django/db/models/sql/query.py