0

对于我的应用程序,我创建了一个SQL 查询构建器,其中包含WhereOrder By子句。我想知道如何对结果进行分页,即我想获得一个关于如何对 SQL 查询的结果进行分页的模板。这个描述可能有点混乱,所以举个例子可能会更容易:

考虑测试表

CREATE TABLE [dbo].[TestTable](
    [RecordID] [int] NOT NULL,
    [ID] [nvarchar](1000) NULL,
    [Name] [nvarchar](1000) NULL,
    [Dept] [nvarchar](1000) NULL
)
INSERT [dbo].[TestTable] 
    SELECT 1, N'1', N'Andy', N'IT'
UNION ALL
    SELECT 2, N'2', N'Bob', N'IT'
UNION ALL
    SELECT 3, N'3', N'Camila', N'Sales'
UNION ALL
    SELECT 4, N'4', N'Drew', N'IT'
UNION ALL
    SELECT 5, N'5', N'Elsie', N'Sales'
UNION ALL
    SELECT 6, N'6', N'Frank', N'IT'
UNION ALL
    SELECT 7, N'7', N'Gaby', N'Sales'
UNION ALL
    SELECT 8, N'8', N'Hank', N'IT'
UNION ALL
    SELECT 9, N'9', N'Iris', N'Sales'
UNION ALL
    SELECT 10, N'8', N'John', N'IT'

假设我有一个Where子句:

WHERE  ([Dept] = 'IT')

以及按条款订购:

ORDER BY [Name] DESC

我试图通过使用类似的东西来进行分页:

SELECT [RECORDID], [ID], [Name], [Dept], RowNum  
    FROM (
            SELECT [RECORDID], [ID], [Name], [Dept], 
                    ROW_NUMBER() OVER (ORDER BY [RecordID]) AS RowNum 
            FROM [TestTable] WHERE  ([Dept] = 'IT') 
        ) AS [TestTable_DerivedTable] 
WHERE [TestTable_DerivedTable].RowNum BETWEEN 3 AND 6 ORDER BY [Name] DESC

这不起作用,因为我无法ORDER BY [Name] DESC进入[TestTable_DerivedTable]. 如果我只有WHERE子句,它将返回名称:

安迪、鲍勃、德鲁、弗兰克、汉克和约翰。

如果我输入分页,即BETWEEN 3 AND 6,我正确地得到:

德鲁、弗兰克、汉克和约翰

如何添加ORDER BY [Name] DESC以便获得(首先是反转,然后是分页)

弗兰克、德鲁、鲍勃和安迪

4

1 回答 1

2

如果将 移到ORDER BY [Name] DESCWindow 函数中,您将得到您想要的:

SELECT [RECORDID], [ID], [Name], [Dept], RowNum  
FROM
(
   SELECT [RECORDID], [ID], [Name], [Dept]
      , ROW_NUMBER() OVER (ORDER BY [Name] DESC) AS RowNum 
   FROM [TestTable] WHERE  ([Dept] = 'IT') 
) AS [TestTable_DerivedTable] 
WHERE [TestTable_DerivedTable].RowNum BETWEEN 3 AND 6
于 2012-10-24T00:28:12.670 回答