MSSQL 2012 & 2008 分頁與計數

  • 580
  • 0
  • SQL
  • 2022-02-24

筆記一下 MSSQL 新版分頁功能語法

2012 支援 OFFSET ROWS

MSSQL 2012

SELECT col1, col2, ...
 FROM ...
 WHERE ... 
 ORDER BY -- this is a MUST there must be ORDER BY statement
-- the paging comes here
OFFSET     10 ROWS       -- skip 10 rows
FETCH NEXT 10 ROWS ONLY; -- take 10 rows

Example:

SELECT ROW_NUMBER() OVER(ORDER BY Id) AS RowNumber,* 
FROM Users
WHERE (@IsDeleted IS NULL OR IsDeleted=@IsDeleted) 
ORDER BY Id
OFFSET     @Skip ROWS
FETCH NEXT @Take ROWS ONLY;

MSSQL 2008

SELECT *
FROM(
	SELECT *,
		--先用ROW_NUMBER()替每筆資料設定編號
		ROW_NUMBER() OVER(ORDER BY EmployeeId DESC) AS rowNumber,
		--再用COUNT()依照欄位分別計數
		COUNT(*) OVER(PARTITION BY DepartmentId) AS Total
	FROM EmployeeAndDepartmentData
	WHERE DepartmentId = 1) TempTable
--最後找出編號介於5-10的資料
WHERE rowNumber BETWEEN 5 AND 10

參照 

sql - Implement paging (skip / take) functionality with this query - Stack Overflow

https://ithelp.ithome.com.tw/articles/10190424

PS5