code: def _group_sql(self, quote_char=None, groupby_alias=True, **kwargs):
          
          clauses = []
          selected_aliases = {s.alias for s in self._selects}
          for field in self._groupbys:
              if groupby_alias and field.alias and field.alias in selected_aliases:
                  clauses.append("{quote}{alias}{quote}".format(
                        alias=field.alias,
                        quote=quote_char or '',
                  ))
              else:
                  clauses.append(field.get_sql(quote_char=quote_char, **kwargs))
  
          sql = ' GROUP BY {groupby}'.format(groupby=','.join(clauses))
          if self._with_totals:
              return sql + ' WITH TOTALS'
          return sql
docs: Produces the GROUP BY part of the query.  This is a list of fields. The clauses are stored in the query under
          self._groupbys as a list fields.
  
          If an groupby field is used in the select clause,
          determined by a matching alias, and the groupby_alias is set True
          then the GROUP BY clause will use the alias,
          otherwise the entire field will be rendered as SQL.