查找部门内员工的平均工资偏差

时间:2015-06-01 06:30:15

标签: mysql sql sqlite

我有一份在一组团队中工作的员工名单。我们试图找出每个员工的工资与其部门平均水平的差异。我一直在寻找标准差,但如果我需要一个子选择来实现这一点,我就会陷入困境。

表格如下:

enter image description here

我没有任何代码要显示,因为我总是卡在别名上。

2 个答案:

答案 0 :(得分:1)

在简单的任务中完成任务。让我们先找到平均工资:

Select TeamID, `Year`, AVG(Salary) avgSal
FROM Employees
GROUP BY TeamID, `Year`

现在,为了获得差异,您需要做的就是从平均值中减去员工的薪水:

SELECT e.EmployeeID, e.Salary, a.avgSal, e.Salary - a.avgSal as diff
FROM Employees e
INNER JOIN 
(
    Select TeamID, `Year`, AVG(Salary) avgSal
    FROM Employees
    GROUP BY TeamID, `Year`
) as a
ON a.TeamID = e.TeamID and a.`Year` = e.`Year`

答案 1 :(得分:0)

试试这个:

SELECT T2.EmployeeID,
       T1.TeamID,
       T1.Salary,
       T1.AvgSalary,
       T2.Salary-T1.AvgSalary AS diff 
FROM
    ((SELECT TeamID,AVG(Salary) as AvgSalary,Year
    FROM TableName
    GROUP BY TeamID,Year) T1 JOIN
    (SELECT EmployeeID,TeamID,Salary
    FROM TableName) T2 ON T1.TeamID=T2.TeamID)
GROUP BY T2.EmployeeID,T1.TeamID,T2.Salary

示例结果:

EmployeeID  TeamID  Salary  AvgSalary   diff
1           20      39999   28999       11000
2           22      44999   44999       0
3           20      23999   28999       -5000
4           20      34499   28999       5500
5           20      39559   28999       10560
6           20      33999   28999       5000

SQL Fiddle中的示例结果。