例如,在SQL Server中是否可以获取从第10行到第20行的行? 我的意思是,我通过查询数据库获得了超过1800行,然后我希望将它们显示为10×10。
答案 0 :(得分:2)
使用CTE添加表示每行行号的列,然后按该列过滤。
;WITH MyCTE AS
(
SELECT *,
ROW_NUMBER() OVER(ORDER BY ID) RowNum
FROM Table
)
SELECT *
FROM MyCTE
WHERE RowNum BETWEEN 10 AND 20
答案 1 :(得分:1)
或者在SQL 2012+中,使用OFFSET\FETCH
....
ORDER BY ...
OFFSET 10 ROWS
FETCH NEXT 10 ROWS;
请参阅http://msdn.microsoft.com/en-us/library/ms188385%28v=SQL.110%29.aspx
答案 2 :(得分:0)
示例:
WITH ResultSetWithRowNumber AS
(
SELECT ROW_NUMBER() OVER(ORDER BY MyField1) AS RowNumber, MyField1, MyField2
FROM MyTable
WHERE MyField2 = SomeValue
)
SELECT RowNumber, MyField1, MyField2
FROM ResultSetWithRowNumber
WHERE RowNumber BETWEEN 10 AND 20