SQL: Return 分页记录并获取所有记录的计数
SQL: Return paged records and also get count of all records
这是我的查询的简化版本:
select myCol1, mycol2 from MyTable where mycol3 = 'blah'
OFFSET (@skip) rows fetch next (@take) rows only
这按预期工作,但我正在尝试对其进行修改,以便我也得到返回给我的所有找到的记录的完整计数。这是我目前的尝试,但是 DataCount
总是 returns 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
您可以使用 window 函数:
select myCol1, mycol2, count(*) over() dataCount
from MyTable
where mycol3 = 'blah'
order by ??
offset (@skip) rows fetch next (@take) rows only
请注意,您的查询似乎缺少 order by
子句 - 没有它,结果集中记录的排序方式是不确定的,这可能会在多次执行同一查询时导致结果不一致(这很可能会在您传呼时发生)。
这是我的查询的简化版本:
select myCol1, mycol2 from MyTable where mycol3 = 'blah'
OFFSET (@skip) rows fetch next (@take) rows only
这按预期工作,但我正在尝试对其进行修改,以便我也得到返回给我的所有找到的记录的完整计数。这是我目前的尝试,但是 DataCount
总是 returns 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
您可以使用 window 函数:
select myCol1, mycol2, count(*) over() dataCount
from MyTable
where mycol3 = 'blah'
order by ??
offset (@skip) rows fetch next (@take) rows only
请注意,您的查询似乎缺少 order by
子句 - 没有它,结果集中记录的排序方式是不确定的,这可能会在多次执行同一查询时导致结果不一致(这很可能会在您传呼时发生)。