使用AdventureWorks2012
数据库
步骤1:执行以下查询:
select *
from
(select
ROW_NUMBER() OVER(order by listprice desc) AS RowNumber,*
from Production.Product) as a
where
a.RowNumber between 1 and 2
select *
from Production.Product
order by ListPrice desc
offset 0 rows fetch next 2 rows only
select top 2 Productid, ListPrice
from Production.Product
order by ListPrice desc
步骤2:现在执行以下查询:
select *
from
(select
ROW_NUMBER() OVER(order by listprice asc) AS RowNumber,*
from Production.Product) as a
where
a.RowNumber between 1 and 2
select *
from Production.Product
order by ListPrice asc
offset 0 rows fetch next 2 rows only
select top 2 Productid, ListPrice
from Production.Product
order by ListPrice asc
在这两种情况下查看产品 ID(对于 DESC 和 ASC)
这并不奇怪。 您了解到的是,多行具有相同的listprice
值。 当listprice
有平局时,相同值的键的排序是不确定的。
换句话说,SQL Server(以及一般的数据库)中的排序并不稳定。 多次运行同一查询可能会返回不同的顺序。 同样,对查询的微小更改可能会导致不同的顺序 - 对于具有相同值的键。
这其实很容易理解。 SQL 表表示无序集。 因此,它们没有自然顺序。 数据库无法对具有相同键值的行进行规范排序。
要解决此问题,只需在排序中添加一个唯一 id,如下所示:
order by listprice desc, productid
添加其他唯一键可使排序稳定。