def as_sql(self, with_limits=True, with_col_aliases=False):
        # Django #12192 - Don't execute any DB query when QS slicing results in limit 0
        if with_limits and self.query.low_mark == self.query.high_mark:
            return '', ()
        
        self._fix_aggregates()
        
        self._using_row_number = False
        
        # Get out of the way if we're not a select query or there's no limiting involved.
        check_limits = with_limits and (self.query.low_mark or self.query.high_mark is not None)
        if not check_limits:
            # The ORDER BY clause is invalid in views, inline functions, 
            # derived tables, subqueries, and common table expressions, 
            # unless TOP or FOR XML is also specified.
            try:
                setattr(self.query, '_mssql_ordering_not_allowed', with_col_aliases)
                result = super(SQLCompiler, self).as_sql(with_limits, with_col_aliases)
            finally:
                # remove in case query is every reused
                delattr(self.query, '_mssql_ordering_not_allowed')
            return result

        raw_sql, fields = super(SQLCompiler, self).as_sql(False, with_col_aliases)
        
        # Check for high mark only and replace with "TOP"
        if self.query.high_mark is not None and not self.query.low_mark:
            if self.connection.ops.is_db2:
                sql = self._select_top('', raw_sql, self.query.high_mark)
            else:
                _select = 'SELECT'
                if self.query.distinct:
                    _select += ' DISTINCT'
                sql = re.sub(r'(?i)^{0}'.format(_select), '{0} TOP {1}'.format(_select, self.query.high_mark), raw_sql, 1)
            return sql, fields
            
        # Else we have limits; rewrite the query using ROW_NUMBER()
        self._using_row_number = True

        # Lop off ORDER... and the initial "SELECT"
        inner_select = _remove_order_limit_offset(raw_sql)
        outer_fields, inner_select = self._alias_columns(inner_select)

        order = _get_order_limit_offset(raw_sql)[0]

        qn = self.connection.ops.quote_name
        inner_table_name = qn('AAAA')

        outer_fields, inner_select, order = self._fix_slicing_order(outer_fields, inner_select, order, inner_table_name)
        
        # map a copy of outer_fields for injected subselect
        f = []
        for x in outer_fields.split(','):
            i = x.upper().find(' AS ')
            if i != -1:
                x = x[i+4:]
            if x.find('.') != -1:
                tbl, col = x.rsplit('.', 1)
            else:
                col = x
            f.append('{0}.{1}'.format(inner_table_name, col.strip()))

        # inject a subselect to get around OVER requiring ORDER BY to come from FROM
        inner_select = '{fields} FROM ( SELECT {inner} ) AS {inner_as}'.format(
            fields=', '.join(f),
            inner=inner_select,
            inner_as=inner_table_name,
        )
        
        # IBM's DB2 cannot have a prefix of `_` for column names
        row_num_col = 'django_pyodbc_row_num' if self.connection.ops.is_db2 else '_row_num'
        where_row_num = '{0} < {row_num_col}'.format(self.query.low_mark, row_num_col=row_num_col)
        if self.query.high_mark:
            where_row_num += ' and {row_num_col} <= {0}'.format(self.query.high_mark, row_num_col=row_num_col)
        
        # SQL Server 2000 doesn't support the `ROW_NUMBER()` function, thus it
        # is necessary to use the `TOP` construct with `ORDER BY` so we can
        # slice out a particular range of results.
        if self.connection.ops.sql_server_ver < 2005 and not self.connection.ops.is_db2:
            num_to_select = self.query.high_mark - self.query.low_mark
            order_by_col_with_prefix,order_direction = order.rsplit(' ',1)
            order_by_col = order_by_col_with_prefix.rsplit('.',1)[-1]
            opposite_order_direction = REV_ODIR[order_direction]
            sql = r'''
                SELECT 
                1, -- placeholder for _row_num
                * FROM
                (
                    SELECT TOP
                    -- num_to_select
                    {num_to_select}
                    *
                    FROM
                    (
                        SELECT TOP 
                        -- high_mark
                        {high_mark}
                        -- inner
                        {inner}
                        ORDER BY (
                        -- order_by_col
                        {left_sql_quote}AAAA{right_sql_quote}.{order_by_col}
                        ) 
                        -- order_direction
                        {order_direction}
                    ) AS BBBB ORDER BY ({left_sql_quote}BBBB{right_sql_quote}.{order_by_col}) {opposite_order_direction}
                ) AS QQQQ ORDER BY ({left_sql_quote}QQQQ{right_sql_quote}.{order_by_col}) {order_direction}
                '''.format(
                    inner=inner_select,
                    num_to_select=num_to_select,
                    high_mark=self.query.high_mark,
                    order_by_col=order_by_col,
                    order_direction=order_direction,
                    opposite_order_direction=opposite_order_direction,
                    left_sql_quote=self.connection.ops.left_sql_quote,
                    right_sql_quote=self.connection.ops.right_sql_quote,
                )
        else:
            sql = "SELECT {row_num_col}, {outer} FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY {order}) as {row_num_col}, {inner}) as QQQ where {where}".format(
                outer=outer_fields,
                order=order,
                inner=inner_select,
                where=where_row_num,
                row_num_col=row_num_col
            )
        
        
        return sql, fields
dataset/ETHPy150Open lionheart/django-pyodbc/django_pyodbc/compiler.py/SQLCompiler.as_sql/original