SQL获得每个国家/地区人员工作工资的平均值

时间:2012-12-14 17:25:18

标签: sql sql-server database sql-server-2008

Microsoft SQL Server 2008

一名工人住在某个国家,可能有一份以上的工作,薪水不止一个。

我想得到每个国家个人总薪水的平均值。

表:

1)国家/地区(country_id,姓名)

2)人(ssn,name,country_id)

3)工作(ssn,job_title,salary)

[国家]

  • 1,美国
  • 2,德国

[人]

  • 010101,John,1
  • 020202,Lee,1
  • 030303,Harry,2

[作业]

  • 010101,老师,3200
  • 010101,builder,1500
  • 020202,演员,45000
  • 020202,歌手,200000
  • 030303,制片人,120000

需要的查询结果:

每个国家/地区的平均值(每个国家/地区)=每个工人总工资的总和)/工人数量

国家/地区 - 平均工资

  • usa - 124850
  • 德国 - 120000

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT c.name, sum(j.salary)/count(distinct p.ssn) as Avg_Sal 
FROM Countries c
INNER JOIN people p ON c.country_id = p.country_id
INNER JOIN Jobs j on p.ssn = j.ssn
group by c.name

答案 1 :(得分:1)

这应该适合你:

select Salary / count(c.name) AvgSalary, c.Name
from people p
inner join 
(
  select sum(salary) Salary, p.country_id
  from jobs j
  left join people p
    on j.ssn = p.ssn
  group by p.country_id
) sal
  on p.country_id = sal.country_id
left join countries c
  on p.country_id = c.country_id
group by salary, c.Name;

请参阅SQL Fiddle with Demo

答案 2 :(得分:0)

这将完全成功,

with
country as
(select c.country_id,c.name name,p.ssn ssn from countries c,people p where c.country_id=p.country_id),
sal1 as
(select sum(salary) salary,j.ssn ssn from people p,jobs j where p.ssn=j.ssn group by j.ssn)
select country.name,avg(sal1.salary) from sal1,country where sal1.ssn=country.ssn group by country.name;

sqlfiddle

使用with子句将更具可读性和可理解性。