Sql server SQL Server:AdventureWorks中男女员工的平均费率

Sql server SQL Server:AdventureWorks中男女员工的平均费率,sql-server,aggregate-functions,adventureworks,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.Business

我试图写一个查询,在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;

我正试图这样做,以便更好地了解函数的工作原理,只需按
性别进行分组,而不是按性别和比率进行分组:

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
进行分组,这是您的平均值-不要这样做。此外,公共表表达式实际上并不填充任何函数,因此也可以将其删除:

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;
-在ANSI-92 SQL标准中(20多年前),旧样式的逗号分隔表列表样式被正确的ANSI
JOIN
语法所取代,不鼓励使用它