对于我的应用程序,我创建了一个 SQL查询构建器,其中包含 Where 和 Order 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
以便我获得(首先是反转,然后是分页):
弗兰克,德鲁,鲍勃和安迪
答案 0 :(得分:2)
如果将ORDER BY [Name] DESC
移动到Window功能中,您将获得所需内容:
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