How to properly use the Sql Server ROW_NUMBER function with ordered queries?
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 2开发者_StackOverflow中文版0 * from dbo.ProcessoInstanciaFonte as p order by p.DtDistribuicao
They both should return the same rows but aren't. What is the problem?
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):
SELECT *
FROM
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY p.DtDistribuicao, p.Id) AS RowNumber
FROM ProcessoInstanciaFonte as p
) AS q
WHERE q.RowNumber BETWEEN 1 AND 20;
ORDER BY q.RowNumber
SELECT TOP 20 *
FROM dbo.ProcessoInstanciaFonte AS p
ORDER BY p.DtDistribuicao, p.Id
精彩评论