是否可以获取单个记录的 PERCENT_RANK,但相对于整个 table?
Is it possible to get the PERCENT_RANK for a single record, but relative to the entire table?
我想要单个记录的 PERCENT_RANK
值,但与整个 table 相关。这可能吗?
我见过的例子是这样的:
SELECT Name, Salary
PERCENT_RANK() OVER (ORDER BY Salary)
FROM Employees
请注意,它正在计算 returned 记录集 的百分位数。如果您 return 阅读整个 table,那就太好了。但是,如果您 return 是一个子集,那么您只会在 returned 记录集 中获得一行 的百分位数它用于整个 table(对于一组行,我 不 return)。
文档是这样说的:
Calculates the relative rank of a row within a group of rows
这不是我想要的。基本上,我想这样做(注意:这是非工作代码):
SELECT Name, Salary
PERCENT_RANK() OVER (SELECT * FROM Employees ORDER BY Salary)
FROM Employees
所以,实际上,我想说,"Give me the percentile of this record when compared to the entire table."
在上面的例子中,它是一样的,因为我要检索整个 table。但是我无法提取单个记录并获得其作为整体 table 的百分位排名。
SELECT Name, Salary
PERCENT_RANK() OVER (ORDER BY Salary)
FROM Employees
WHERE id = 1234
那条记录将始终是 1.000
,因为它在所有行的 100% 百分位 returned,这只是一个。
是的,您需要使用子查询或 CTE:
WITH CTE AS
(SELECT id,
[Name],
Salary,
PERCENT_RANK() OVER (ORDER BY Salary) AS PR
FROM Employees)
SELECT [Name],
Salary,
PR
FROM CTE
WHERE id = 1234;
SELECT e.Name, e.Salary, r.Employee_Rank
FROM Employees e
JOIN (
SELECT id,
PERCENT_RANK() OVER (ORDER BY Salary) AS Employee_Rank
FROM Employees
) r ON r.Id = e.Id
WHERE e.id = 1234
我想要单个记录的 PERCENT_RANK
值,但与整个 table 相关。这可能吗?
我见过的例子是这样的:
SELECT Name, Salary
PERCENT_RANK() OVER (ORDER BY Salary)
FROM Employees
请注意,它正在计算 returned 记录集 的百分位数。如果您 return 阅读整个 table,那就太好了。但是,如果您 return 是一个子集,那么您只会在 returned 记录集 中获得一行 的百分位数它用于整个 table(对于一组行,我 不 return)。
文档是这样说的:
Calculates the relative rank of a row within a group of rows
这不是我想要的。基本上,我想这样做(注意:这是非工作代码):
SELECT Name, Salary
PERCENT_RANK() OVER (SELECT * FROM Employees ORDER BY Salary)
FROM Employees
所以,实际上,我想说,"Give me the percentile of this record when compared to the entire table."
在上面的例子中,它是一样的,因为我要检索整个 table。但是我无法提取单个记录并获得其作为整体 table 的百分位排名。
SELECT Name, Salary
PERCENT_RANK() OVER (ORDER BY Salary)
FROM Employees
WHERE id = 1234
那条记录将始终是 1.000
,因为它在所有行的 100% 百分位 returned,这只是一个。
是的,您需要使用子查询或 CTE:
WITH CTE AS
(SELECT id,
[Name],
Salary,
PERCENT_RANK() OVER (ORDER BY Salary) AS PR
FROM Employees)
SELECT [Name],
Salary,
PR
FROM CTE
WHERE id = 1234;
SELECT e.Name, e.Salary, r.Employee_Rank
FROM Employees e
JOIN (
SELECT id,
PERCENT_RANK() OVER (ORDER BY Salary) AS Employee_Rank
FROM Employees
) r ON r.Id = e.Id
WHERE e.id = 1234