Row_Number Over Where RowNumber between

后端 未结 2 1830
耶瑟儿~
耶瑟儿~ 2021-01-05 23:53

I\'m try to select a certain rows from my table using the row_number over. However, the sql will prompt the error msg \"Invalid column name \'ROWNUMBERS\' \". Anyone can cor

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 00:27

    Attempting to reference the aliased column in the WHERE clause does not work because of the logical query processing taking place. The WHERE is evaluated before the SELECT clause. Therefore, the column ROWNUMBERS does not exist when WHERE is evaluated.

    The correct way to reference the column in this example would be:

    SELECT a.*
    FROM
        (SELECT ROW_NUMBER() OVER (ORDER BY  Price ASC) AS ROWNUMBERS, * 
        FROM Product) a
    WHERE a.ROWNUMBERS BETWEEN @fromCount AND @toCount
    

    For your reference, the order for operations is:

    1. FROM
    2. WHERE
    3. GROUP BY
    4. HAVING
    5. SELECT
    6. ORDER BY

提交回复
热议问题