'Returns a tuple representing the SQL elements in the "group by" clause.'

def get_grouping(self, having_group_by, ordering_group_by):

    qn = self.quote_name_unless_alias
    (result, params) = ([], [])
    if (self.query.group_by is not None):
        select_cols = (self.query.select + self.query.related_select_cols)
        select_cols = [s[0] for s in select_cols]
        if ((len(self.query.get_meta().concrete_fields) == len(self.query.select)) and self.connection.features.allows_group_by_pk):
            self.query.group_by = [(self.query.get_meta().db_table, self.query.get_meta().pk.column)]
            select_cols = []
        seen = set()
        cols = ((self.query.group_by + having_group_by) + select_cols)
        for col in cols:
            col_params = ()
            if isinstance(col, (list, tuple)):
                sql = ('%s.%s' % (qn(col[0]), qn(col[1])))
            elif hasattr(col, 'as_sql'):
                (sql, col_params) = col.as_sql(qn, self.connection)
            else:
                sql = ('(%s)' % str(col))
            if (sql not in seen):
                result.append(sql)
                params.extend(col_params)
                seen.add(sql)
        if (ordering_group_by and (not self.connection.features.allows_group_by_pk)):
            for (order, order_params) in ordering_group_by:
                if ((order not in seen) or order_params):
                    result.append(order)
                    params.extend(order_params)
                    seen.add(order)
        for (extra_select, extra_params) in self.query.extra_select.values():
            sql = ('(%s)' % str(extra_select))
            result.append(sql)
            params.extend(extra_params)
    return (result, params)
