时间:2022-06-17 08:35:18 | 栏目:MsSql | 点击:次
根据SalesOrderID排序,取第16-18行这3条记录。
SELECT TOP 3 [SalesOrderID], [RevisionNumber], [OrderDate] FROM [AdventureWorks2012].[Sales].[SalesOrderHeader] WHERE [SalesOrderID] NOT IN ( SELECT TOP 15 [SalesOrderID] FROM [AdventureWorks2012].[Sales].[SalesOrderHeader] ORDER BY [SalesOrderID] ) ORDER BY SalesOrderID;
备注: 注意前后的order by 一致
SELECT [SalesOrderID], [RevisionNumber], [OrderDate] FROM ( SELECT [SalesOrderID], [RevisionNumber], [OrderDate] , ROW_NUMBER() OVER ( ORDER BY SalesOrderID ) AS rowid FROM [AdventureWorks2012].[Sales].[SalesOrderHeader] ) cte WHERE rowid BETWEEN 16 AND 18;
SELECT [SalesOrderID], [RevisionNumber], [OrderDate] FROM [AdventureWorks2012].[Sales].[SalesOrderHeader] ORDER BY SalesOrderID OFFSET 15 ROW FETCH NEXT 3 ROWS ONLY;
DECLARE @page INT, @size INT, @Total INT; SELECT @page = 3, @size = 10; --当前页面为3,页面大小为10 -------方法一 SELECT TOP ( @size ) [SalesOrderID], [RevisionNumber], [OrderDate] FROM [AdventureWorks2012].[Sales].[SalesOrderHeader] WHERE [SalesOrderID] NOT IN ( SELECT TOP (( @page - 1 ) * @size ) [SalesOrderID] FROM [AdventureWorks2012].[Sales].[SalesOrderHeader] ORDER BY [SalesOrderID] ) ORDER BY SalesOrderID; -------方法二 SELECT [SalesOrderID], [RevisionNumber], [OrderDate] FROM ( SELECT [SalesOrderID], [RevisionNumber], [OrderDate] , ROW_NUMBER() OVER ( ORDER BY SalesOrderID ) AS rowid FROM [AdventureWorks2012].[Sales].[SalesOrderHeader] ) cte WHERE rowid BETWEEN ( @page - 1 ) * @size + 1 AND @page * @size; -------方法三 SELECT [SalesOrderID], [RevisionNumber], [OrderDate] FROM [AdventureWorks2012].[Sales].[SalesOrderHeader] ORDER BY SalesOrderID OFFSET ( @page - 1 ) * @size ROWS FETCH NEXT @size ROWS ONLY; ---offset的当前页面是从零开