它的计算方式如下:(分组内当前行的 Rank 值-1) / (分组内总行数 - 1)
USE AdventureWorks
GO
SELECT SalesOrderID, OrderQty,
RANK() OVER(ORDER BY SalesOrderID) Rnk,
PERCENT_RANK() OVER(ORDER BY SalesOrderID) AS PctDist
FROM Sales.SalesOrderDetail
WHERE SalesOrderID IN (43670, 43669, 43667, 43663)
ORDER BY PctDist DESC
GO
执行上述查询后,返回以下结果:
从上述可与看到,对PERCENT_RANK()函数的查询中也包含了 Rank() 函数,之所以这样写,是希望通过 Rank 函数来反应PERCENT_RANK()函数具体功能。
接下来让我们在查询中加入分区,查询代码如下:
USE AdventureWorks
GO
SELECT SalesOrderID, OrderQty, ProductID,
RANK() OVER(PARTITION BY SalesOrderID ORDER BY ProductID ) Rnk,
PERCENT_RANK() OVER(PARTITION BY SalesOrderID ORDER BY ProductID ) AS PctDist
FROM Sales.SalesOrderDetail s
WHERE SalesOrderID IN (43670, 43669, 43667, 43663)
--ORDER BY PctDist DESC
GO
如下图所示,我们会发现 PERCENT_RANK() 函数其实就是对具有相同 Order By 字段在其所在的 Partition 组中出现的概率。