如何从SELECT查询顶部返回一定数量的行?
我的意思是,假设我有一个1000行的表。假设我想要前50行,那么我想要第二行50行,然后是第三行50行,依此类推。我知道TOP或LIMIT会限制返回的行数,但我不确定如何告诉SQL从返回表中的某一点获取行。
答案 0 :(得分:1)
在Sql server中,您可以使用ROW_NUMBER()
函数来执行您想要的操作
SELECT ROW_NUMBER() OVER(ORDER BY col3 DESC) AS Row,
col1, col2, col3
FROM tablename
简而言之
WITH ctetable AS
(
SELECT ROW_NUMBER() OVER(ORDER BY col3 DESC) AS RowNumber ,
col1, col2, col3
FROM tablename
)
SELECT *
FROM ctetable
WHERE RowNumber BETWEEN 1 AND 50;
答案 1 :(得分:0)
SELECT TOP 50 * FROM
(
SELECT ROW_NUMBER() OVER(ORDER BY ID DESC) AS [Index], * FROM MyTable
) AS A
WHERE A.[Index] BETWEEN @StartIndex AND @EndIndex
答案 2 :(得分:0)
;With CTE as(SELECT ROW_NUMBER() OVER(ORDER BY (select 0)) AS rno, * FROM MyTable)
select * from CTE where rno between start and end;