Using ranking-function derived column in where clause (SQL Server 2008)

后端 未结 3 863
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-15 12:31

Hoping this is trivial for a SQL-Ninja... Been trying to get the following query working:

This is for SQL Server 2008

SELECT 
    ROW_NUMBER() OVER (ORD         


        
3条回答
  •  忘掉有多难
    2021-02-15 13:18

    You must move the WHERE operator above the project list where RowNumber column is created. Use a derived table or a CTE:

    SELECT * 
      FROM (
       SELECT *, ROW_NUMBER() OVER (...) as RowNumber
       FROM ...) As ...
     WHERE RowNumber = ...
    

    the equivalent CTE is:

    WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (...) as RowNumber
           FROM ...)
    SELECT * FROM cte 
    WHERE RowNumber = ...   
    

提交回复
热议问题