A.对分区中的行进行排名
以下示例按照数量对指定清单位置的清单中的产品进行了排名。
结果集按 LocationID 分区并在逻辑上按 Quantity 排序。
注意,产品 494 和 495 具有相同的数量。 因为它们是关联的,所以两者均排名第一。
USE AdventureWorks2012; GO SELECT i.ProductID, p.Name, i.LocationID, i.Quantity ,RANK() OVER (PARTITION BY i.LocationID ORDER BY i.Quantity DESC) AS Rank FROM Production.ProductInventory AS i INNER JOIN Production.Product AS p ON i.ProductID = p.ProductID WHERE i.LocationID BETWEEN 3 AND 4 ORDER BY i.LocationID; GO
下面是结果集:
ProductID Name LocationID Quantity Rank ----------- ---------------------- ------------ -------- ---- 494 Paint - Silver 3 49 1 495 Paint - Blue 3 49 1 493 Paint - Red 3 41 3 496 Paint - Yellow 3 30 4 492 Paint - Black 3 17 5 495 Paint - Blue 4 35 1 496 Paint - Yellow 4 25 2 493 Paint - Red 4 24 3 492 Paint - Black 4 14 4 494 Paint - Silver 4 12 5 (10 row(s) affected)
B.对结果集中的所有行排名
下面的示例返回按薪金排名的前十名员工。 因为未指定 PARTITION BY 子句,所以,RANK 函数应用于结果集中的所有行。
USE AdventureWorks2012 SELECT TOP(10) BusinessEntityID, Rate, RANK() OVER (ORDER BY Rate DESC) AS RankBySalary FROM HumanResources.EmployeePayHistory AS eph1 WHERE RateChangeDate = (SELECT MAX(RateChangeDate) FROM HumanResources.EmployeePayHistory AS eph2 WHERE eph1.BusinessEntityID = eph2.BusinessEntityID) ORDER BY BusinessEntityID;
下面是结果集:
BusinessEntityID Rate RankBySalary ---------------- --------------------- -------------------- 1 125.50 1 2 63.4615 4 3 43.2692 8 4 29.8462 19 5 32.6923 16 6 32.6923 16 7 50.4808 6 8 40.8654 10 9 40.8654 10 10 42.4808 9
时间: 2024-11-03 09:50:25