SQL Row_Number() function in Where Clause

后端 未结 10 1477
野性不改
野性不改 2020-12-02 16:11

I found one question answered with the Row_Number() function in the where clause. When I tried one query, I was getting the following error:

相关标签:
10条回答
  • 2020-12-02 17:01

    Using CTE (SQL Server 2005+):

    WITH employee_rows AS (
      SELECT t.employee_id,
             ROW_NUMBER() OVER ( ORDER BY t.employee_id ) 'rownum'
        FROM V_EMPLOYEE t)
    SELECT er.employee_id
      FROM employee_rows er
     WHERE er.rownum > 1
    

    Using Inline view/Non-CTE Equivalent Alternative:

    SELECT er.employee_id
      FROM (SELECT t.employee_id,
                   ROW_NUMBER() OVER ( ORDER BY t.employee_id ) 'rownum'
              FROM V_EMPLOYEE t) er
     WHERE er.rownum > 1
    
    0 讨论(0)
  • 2020-12-02 17:04
    SELECT  employee_id
    FROM    (
            SELECT  employee_id, ROW_NUMBER() OVER (ORDER BY employee_id) AS rn
            FROM    V_EMPLOYEE
            ) q
    WHERE   rn > 0
    ORDER BY
            Employee_ID
    

    Note that this filter is redundant: ROW_NUMBER() starts from 1 and is always greater than 0.

    0 讨论(0)
  • 2020-12-02 17:05

    I think you want something like this:

    SELECT employee_id 
    FROM  (SELECT employee_id, row_number() 
           OVER (order by employee_id) AS 'rownumber' 
           FROM V_EMPLOYEE) TableExpressionsMustHaveAnAliasForDumbReasons
    WHERE rownumber > 0
    
    0 讨论(0)
  • 2020-12-02 17:08

    I feel like all the answers showing use of a CTE or Sub Query are sufficient fixes for this, but I don't see anyone getting to the heart of why OP has a problem. The reason why what OP suggested doesn't work is due to logical query processing order here:

    1. FROM
    2. ON
    3. JOIN
    4. WHERE
    5. GROUP BY
    6. WITH CUBE/ROLLUP
    7. HAVING
    8. SELECT
    9. DISTINCT
    10. ORDER BY
    11. TOP
    12. OFFSET/FETCH

    I believe this contributes to the answer greatly, because it explains why issues like this one occur. WHERE is always processed before SELECT making a CTE or Sub Query necessary for many functions. You will see this a lot in SQL Server.

    0 讨论(0)
提交回复
热议问题