SQL ROW_NUMBER()问题与分页

时间:2012-05-26 09:14:32

标签: sql sql-server database tsql row-number

我使用ROW_NUMBER()函数从数据库表中获取50个50项 @From参数是从中开始抓取50行的行。 (第一次是51,101,151等1) 我将参数@CityId传递给存储过程,如果数据库中的前60行是cityId=1cityId = 2在第61行,则此存储过程不会返回结果。
但是,如果我通过@From参数51而不是返回结果。 我在这里做错了什么?

SELECT  RowConstrainedResult.*
FROM    ( SELECT    ROW_NUMBER() OVER 
( ORDER BY f.ItemCreatedOnDate DESC ) AS RowNum, 
f.*
FROM (
SELECT
      t.ItemIdId,
      t.ItemTypeId,
      t.CreatedOnDate as ItemCreatedOnDate,
      t.CityId as CityId
FROM   dbo.Items    as t
) f) AS RowConstrainedResult
WHERE   RowNum >= @From
    AND RowNum < @From + 50
    AND CityId = @CityId

2 个答案:

答案 0 :(得分:7)

在您的版本中,ROW_NUMBER()枚举所有行。将cityid的谓词移到最里面的选择,而ROW_NUMBER()只会枚举cityid = 2的行。

SELECT RowConstrainedResult.*
FROM (
     SELECT ROW_NUMBER() OVER (ORDER BY f.ItemCreatedOnDate DESC) AS RowNum, 
            f.*
     FROM (
          SELECT t.ItemIdId,
                 t.ItemTypeId,
                 t.CreatedOnDate as ItemCreatedOnDate,
                 t.CityId as CityId
          FROM dbo.Items AS t
          WHERE CityId = @CityId
          ) AS f
     ) AS RowConstrainedResult
WHERE RowNum >= @From AND 
      RowNum < @From + 50

答案 1 :(得分:2)

我想你想要做的是在内部选择查询中过滤CityId,如下所示:

SELECT  RowConstrainedResult.*
FROM    ( SELECT    ROW_NUMBER() OVER 
( ORDER BY f.ItemCreatedOnDate DESC ) AS RowNum, 
f.*
FROM (
SELECT
      t.ItemIdId,
      t.ItemTypeId,
      t.CreatedOnDate as ItemCreatedOnDate,
      t.CityId as CityId
FROM   dbo.Items    as t
WHERE CityId = @CityId
) f) AS RowConstrainedResult
WHERE   RowNum >= @From
    AND RowNum < @From + 50