SQL 服务器:AdventureWorks 中男性和女性员工的平均比率

SQL Server: avg rate for male and female employees in 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;

我尝试这样做是为了更好地了解函数的工作原理

仅按 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;

主要问题是您在 rate 上分组,这就是您的平均数 - 不要那样做。此外,常见的 table 表达式并没有真正填充任何函数,因此也可以将其删除:

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;