我想我在SQL Server 2012中发现了一个错误。我有以下复杂查询,它使用CTE和row_number来完成分页,然后是一个子查询,在一个查询中返回总行数:
with data as ( ...complex query with row_number() ... as rowNumber... )
select *, (select count(*) from data) as totalRows
from data
where rowNumber between 1 and 10
我在特定查询中发现的是,如果最终查询返回5行,则totalRows返回为8.但是只有5行。 totalRows怎么能大于返回的行数?我已经尝试过查询提示,例如禁用并行执行计划但不仅速度较慢,而且仍然不正确。我可以做错事还是这个错误?还有另一种方法可以在一个查询中获取计数吗?
答案 0 :(得分:1)
如果不知道查询的内部结构并确保您的分区语句写得很好......
我建议你因为你的where子句而得到分歧。您需要保持一致并使用:
with data as ( ...complex query with row_number() ... as rowNumber... )
select *, (select count(*) from data where rowNumber between 1 and 10) as totalRows
from data
where rowNumber between 1 and 10
或
with data as ( ...complex query with row_number() ... as rowNumber... )
select *, (select count(*) from data) as totalRows
from data