SQL Server:AdventureWorks中男性和女性员工的平均费率

时间:2015-04-26 18:43:58

标签: sql-server aggregate-functions adventureworks

我正在尝试编写查询以查找AdventureWorks数据库中男女员工的平均工资率

我写了这个(下面),但我没有得到预期的结果:

with sub as 
(
   select 
       emp.Gender, emp.VacationHours, pay.Rate
   from 
       HumanResources.Employee emp, HumanResources.EmployeePayHistory pay
   where 
       emp.BusinessEntityID = pay.BusinessEntityID
)
select 
    sub.Gender,
    avg(sub.VacationHours) as vac_hours, 
    avg(sub.Rate) as rate
from 
    sub
group by 
    sub.Gender, Rate;

我正在尝试这样做,这样我就可以更好地理解函数的工作原理

2 个答案:

答案 0 :(得分:2)

主要问题是你正在rate进行分组,这是你的平均值 - 不要这样做。此外,公用表表达式并不真正填充任何函数,因此也可以删除它:

select 
    Gender,
    avg(VacationHours) as vac_hours, 
    avg(Rate) as rate
from 
    HumanResources.Employee emp
join
    HumanResources.EmployeePayHistory pay on emp.BusinessEntityID = pay.BusinessEntityID
group by 
    Gender;

答案 1 :(得分:1)

仅按gender分组 - 不是按性别和费率分组:

with sub AS
(
   select 
       emp.Gender, emp.VacationHours, pay.Rate
   from 
       HumanResources.Employee emp
   inner join 
       HumanResources.EmployeePayHistory pay on emp.BusinessEntityID = pay.BusinessEntityID
)
select 
    sub.Gender,
    avg(sub.VacationHours) as vac_hours, 
    avg(sub.Rate) as rate
from 
    sub
group by 
    sub.Gender;