【问题标题】:SQL: Return paged records and also get count of all recordsSQL:返回分页记录并获取所有记录的计数
【发布时间】:2020-10-19 17:26:33
【问题描述】:

这是我的查询的简化版本:

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

【问题讨论】:

    标签: sql sql-server sql-order-by window-functions sql-limit


    【解决方案1】:

    你可以使用窗口函数:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      • 2013-04-08
      • 2018-09-26
      • 2011-07-06
      • 2013-09-22
      • 1970-01-01
      相关资源
      最近更新 更多