<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def _group_sql(self, quote_char=None, groupby_alias=True, **kwargs):
 """ 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. """

        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