2015-04-26 35 views
1
男性和女性員工平均速率

我想編寫一個查詢找到AdventureWorks數據庫SQL服務器: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; 

我試圖做到這一點,所以我可以更好地瞭解函數是如何工作

+0

[不良習慣踢:使用舊樣式的JOIN(http://sqlblog.com/blogs/aaron_bertrand /archive/2009/10/08/bad-habits-to-kick-using-old-style-joins.aspx) - 舊式*逗號分隔的表*樣式列表被替換爲* proper * ANSI'在ANSI - ** 92 ** SQL標準(**超過20年**前)中使用JOIN'語法,並且不鼓勵使用它 –

回答

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