如何正确使用 Sql Server ROW_NUMBER 函数进行有序查询?
我试图从 MSSQL 中理解 ROW_NUMBER 并取得一些经验。
我有这两个片段:
SELECT *
FROM
(
SELECT *,
ROW_NUMBER() OVER (order by p.DtDistribuicao) AS RowNumber
FROM ProcessoInstanciaFonte as p
) as q
WHERE q.RowNumber BETWEEN 1 AND 20;
并且
select top 20 * from dbo.ProcessoInstanciaFonte as p order by p.DtDistribuicao
它们都应该返回相同的行,但事实并非如此。问题是什么?
I'm trying to understand ROW_NUMBER from MSSQL and making some experiences.
I have these two snippets:
SELECT *
FROM
(
SELECT *,
ROW_NUMBER() OVER (order by p.DtDistribuicao) AS RowNumber
FROM ProcessoInstanciaFonte as p
) as q
WHERE q.RowNumber BETWEEN 1 AND 20;
and
select top 20 * from dbo.ProcessoInstanciaFonte as p order by p.DtDistribuicao
They both should return the same rows but aren't. What is the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜想
p.DtDistribuicao
的值有一些联系。服务器可以自由选择任何绑定值作为“第一个”值,在这种情况下,两个不同的查询可能会给出两个不同的结果。您可以在 ORDER BY 末尾添加一个唯一字段作为决胜局。例如,这两个查询应返回相同的行(假设您有一个名为 Id 的唯一字段):
I guess that the values of
p.DtDistribuicao
have some ties. The server is free to pick any of the tied values as the "first" one and the two different queries could give two different results in this case.You could add a unique field at the end of the ORDER BY as a tie-breaker. For example, these two queries should return the same rows (assuming you have a unique field called Id):