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

后端 未结 3 843
爱一瞬间的悲伤
爱一瞬间的悲伤 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:38

    The Window Functions (of which ROW_NUMBER is the best know) are filled in very late in the query, well after the WHERE clause. Therefore you have to nest it too, in order to filter on it:

    SELECT *
    FROM (
        SELECT ROW_NUMBER() OVER (ORDER BY Date_Time DESC) AS RowNumber, *
        FROM
        ( SELECT T.A_ID, T.User_Name, T.Date_Time, T.Value,
                 U.ID, U.Name, U.Field1, U.Field2,
                 COUNT(U.ID) OVER () AS TotalRows
          FROM 
            TeeTable as T INNER JOIN YouTable AS U
            ON T.U_ID = U.ID
            WHERE T.Value BETWEEN 222 AND 225
        ) Numbered
    )  Filtered
    WHERE RowNumber BETWEEN 1 AND 5
    

    You can also put them in CTE's or Views to get the same effect.

提交回复
热议问题