sql:返回分页记录并获取所有记录的计数

ioekq8ef  于 2021-08-01  发布在  Java
关注(0)|答案(1)|浏览(300)

以下是我的查询的简化版本:

select myCol1, mycol2 from MyTable where mycol3 = 'blah'
OFFSET (@skip) rows fetch next (@take) rows only

这是预期的工作,但我试图修改它,使我得到所有找到的记录返回给我的全部计数。这是我目前的尝试 DataCount 总是返回不正确的1。我哪里出错了?

select t.myCol1, t.mycol2, count(t.id) as DataCount from MyTable t where mycol3 = 'blah'
group by myCol1, myCol2
OFFSET (@skip) rows fetch next (@take) rows only
5rgfhyps

5rgfhyps1#

可以使用窗口函数:

select myCol1, mycol2, count(*) over() dataCount
from MyTable 
where mycol3 = 'blah'
order by ??
offset (@skip) rows fetch next (@take) rows only

请注意,您的查询似乎缺少 order by 子句-如果没有它,就无法定义记录在resultset中的排序方式,当同一查询被多次执行时,可能会导致结果不一致(这很可能发生在您要分页时)。

相关问题