第一个对我不起作用(返回Msg 8120 Column 'Salaries.employeeID' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中),直到我添加group by employeeID
:
SELECT
employeeID as ID,
RANK() OVER (ORDER BY AVG (Salary) DESC) AS Value
FROM Salaries
GROUP BY employeeID
也许,为了更好地理解,它可以等效地重写为:
;with cte as (
SELECT employeeID, AVG (Salary) as AvgSalary
FROM Salaries
GROUP BY employeeID
)
select employeeID as ID
, RANK() OVER (ORDER BY AvgSalary DESC) as Value
--, AvgSalary
from cte
在这种情况下,在 CTE 中计算员工的平均工资,然后使用排名列扩展查询Value
。添加partition by employeeID
到over子句:
;with cte as (
SELECT employeeID, AVG (Salary) as AvgSalary
FROM Salaries
GROUP BY employeeID
)
select employeeID as ID
, RANK() OVER (partition by employeeID ORDER BY AvgSalary DESC) as Value
--, AvgSalary
from cte
将导致Value = 1
结果集中的每一行(这似乎不是试图实现的),因为rank()
将每个 distinct 的编号重置为 1 employeeID
,并且employeeID
在每一行中都是不同的,因为数据是在排名之前由该列聚合的.