SQL Server 2008分页总行数

时间:2016-01-16 11:55:03

标签: sql sql-server sql-server-2008

我看到有一些类似的问题,但我无法找到我理解的答案,因为我不是SQL查询专家。

目前可以获取记录页面:

WITH PAGE AS 
(
   SELECT 
       ROW_NUMBER() OVER (ORDER BY SEQUENCE_NO ASC) AS _ROW_, * 
   FROM mytable
) 
SELECT * 
FROM PAGE 
WHERE _ROW_ BETWEEN 0 AND 25

但是如何修改它以便它还返回与第一个查询匹配的记录总数?

WITH PAGE AS 
(
   SELECT 
       ROW_NUMBER(), COUNT(*) OVER (ORDER BY SEQUENCE_NO ASC) AS _ROW_, _TOTAL_, * 
   FROM mytable
) 
SELECT * 
FROM PAGE 
WHERE _ROW_ BETWEEN 0 AND 25

我收到以下错误:

  

'ROW_NUMBER'附近的语法错误,预期'OVER'

2 个答案:

答案 0 :(得分:3)

这不是正确的语法,您需要为Over使用另一个count子句

试试这个

;WITH PAGE AS 
(
SELECT ROW_NUMBER() OVER(ORDER BY SEQUENCE_NO ASC) AS _ROW_,
       COUNT(*) OVER() AS _TOTAL_, * 
FROM mytable
) 
SELECT * FROM PAGE WHERE _ROW_ BETWEEN 0 AND 25

答案 1 :(得分:0)

使用offset和Fetch

版本

select 
 * from 
test1
order by id 
offset 0 rows fetch first 10 rows only;

以上查询按id列排序,并且不跳过(偏移)任何行,并且给我前10行。

select 
 * from 
test1
order by id 
offset 10  rows fetch next 10 rows only;

上面的查询会跳过前10行,并根据id列顺序

给出下一行10行

我们也可以使用变量

声明@offset int 声明@fetch int

设置@ offset = 10 设置@fetch = 10

select 
 * from 
test1
order by id 
offset (@offset)  rows fetch first (@fetch) rows only;