T-SQL - 限制输出中的行数(ROWS OFFSET)

时间:2017-10-25 14:12:21

标签: sql sql-server tsql sql-server-2012

代码:

DECLARE @TileNumber INT = 0
        , @RowsToReturn INT = 25 ;

;WITH [Num1] AS
    (
        SELECT  [N].[Intrgr]
        FROM    (
                    VALUES
                        ( 0 )
                      , ( 0 )
                      , ( 0 )
                      , ( 0 )
                      , ( 0 )
                      , ( 0 )
                      , ( 0 )
                ) AS [N] ( [Intrgr] )
    )
    , [Num2] AS
    (
        SELECT      [Num] = ROW_NUMBER() OVER ( ORDER BY [N1].[Intrgr] )
        FROM        [Num1] AS [N1]
        CROSS JOIN  [Num1] AS [N2]
    )
SELECT  * INTO #Temp1
FROM    [Num2] ;

;WITH [Num1] AS
    (
        SELECT  [N].[Intrgr]
        FROM    (
                    VALUES
                        ( 0 )
                      , ( 0 )
                      , ( 0 )
                      , ( 0 )
                ) AS [N] ( [Intrgr] )
    )
    , [Num2] AS
    (
        SELECT      [Num] = ROW_NUMBER() OVER ( ORDER BY [N1].[Intrgr] ) + 100
        FROM        [Num1] AS [N1]
        CROSS JOIN  [Num1] AS [N2]
    )
SELECT  * INTO #Temp2
FROM    [Num2] ;

--SELECT * FROM #Temp1 -- 49 Rows
--SELECT * FROM #Temp2 -- 16 Rows

;WITH CTE AS
    (
        SELECT      [Num]
        FROM        #Temp1
        ORDER BY    [Num] OFFSET ( @TileNumber * @RowsToReturn ) ROWS FETCH NEXT @RowsToReturn ROWS ONLY
        UNION ALL
        SELECT      [Num]
        FROM        #Temp2
        ORDER BY    [Num] OFFSET ( @TileNumber * @RowsToReturn ) ROWS FETCH NEXT @RowsToReturn ROWS ONLY
    )
SELECT      [C].[Num]
FROM        CTE [C]
ORDER BY    [C].[Num] OFFSET ( @TileNumber * @RowsToReturn ) ROWS FETCH NEXT @RowsToReturn ROWS ONLY ;


DROP TABLE #Temp1 ;
DROP TABLE #Temp2 ;

描述 当我们UNION ALL时,这个例子总共有65条记录。实际表格数据可能会有所不同。

此示例的预期结果 当@TileNumber为0(第一组25条记录)时,我希望Num 1-25返回

当@tileNumber为1(第25组25条记录)时,我希望Num 26-50返回

当@TileNumber为2(第3组25条记录)时,我希望Num 51-65返回

当@TileNumber为其他任何内容时,不应该返回任何内容。

限制 由于性能原因,CTE中的SELECT必须实现偏移/分页。

更新 行数和#of块的数量因实际数据的大小而异。本例中的65个记录/ 3个图块仅用于测试目的。

1 个答案:

答案 0 :(得分:0)

用以下内容替换最终查询(在注释" select *"命令和DROP TABLE命令之间):

;With CTE
As
(
    SELECT      [Num]
    FROM        #Temp1
    UNION ALL
    SELECT      [Num]
    FROM        #Temp2
)
SELECT      [Num]
FROM        CTE
ORDER BY    [Num] OFFSET ( @TileNumber * @RowsToReturn ) ROWS FETCH NEXT @RowsToReturn ROWS ONLY