                  elif hasattr(col, 'as_sql'):
                      self.compile(col)
                  else:
                      sql = '(%s)' % str(col)
                  if sql not in seen:
                      result.append(sql)
                      params.extend(col_params)
                      seen.add(sql)
  
              # Still, we need to add all stuff in ordering (except if the backend can
 
</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)
                if sql not in seen or col_params:
                  elif hasattr(col, 'as_sql'):
                      self.compile(col)
                  else:
                      sql = '(%s)' % str(col)
                if sql not in seen or col_params:
                      result.append(sql)
                      params.extend(col_params)
                      seen.add(sql)
  
              # Still, we need to add all stuff in ordering (except if the backend can
keep keep keep keep replace 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/compiler.py