1

我在阅读代码时遇到问题

SELECT 
    employeeID as ID,
    RANK() OVER (ORDER BY AVG (Salary) DESC) AS Value 
FROM Salaries 

据说可以得到每个员工的平均工资

我的理解是代码应该是

SELECT 
    employeeID as ID,
    RANK() OVER (Partition By employeeID ORDER BY AVG (Salary) DESC) AS Value 
FROM Salaries 

但上面的代码工作得很好吗?

4

1 回答 1

1

第一个对我不起作用(返回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在每一行中都是不同的,因为数据是在排名之前由该列聚合的.

于 2013-09-02T13:44:21.463 回答