从ROW_NUMBER结果中查询数据

时间:2012-02-28 13:59:08

标签: sql sql-server

您好我正在尝试根据ROW_NUMBER()函数查询数据。

SELECT ROW_NUMBER() OVER(ORDER BY Id) AS CountRow,
ProductId, ProductName, Tracklink, ProductImage, TrackPrice FROM ProductDetails;

我的行包含CountRow列中的数字。现在我想查询这个Alias以查找例如31到40之间的行。但是我收到一条错误,说CountRow不存在。

我如何克服这个问题?

感谢....

3 个答案:

答案 0 :(得分:4)

您无法在WHERE子句中引用别名。将它包装在子查询中,你会没事的:

select *
from
(
    SELECT ROW_NUMBER() OVER(ORDER BY Id) AS CountRow,
    ProductId, ProductName, Tracklink, ProductImage, TrackPrice FROM ProductDetails
) a
where CountRow between 31 and 40

答案 1 :(得分:3)

如果您的DBMS支持cte,您可以这样做:

;WITH CTE
(
    SELECT 
        ROW_NUMBER() OVER(ORDER BY Id) AS CountRow,
        ProductId, 
        ProductName, 
        Tracklink, 
        ProductImage, 
        TrackPrice 
    FROM 
        ProductDetails
)
SELECT
    *
FROM
    CTE
WHERE
    CTE.CountRow between 31 and 40

答案 2 :(得分:2)

SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY Id) AS CountRow,
ProductId, ProductName, Tracklink, ProductImage, TrackPrice FROM ProductDetails) AS A
WHERE CountRow BETWEEN 31 AND 40

希望这有帮助。