Microsoft SQL Server 2008
一名工人住在某个国家,可能有一份以上的工作,薪水不止一个。
我想得到每个国家个人总薪水的平均值。
表:
1)国家/地区(country_id,姓名)
2)人(ssn,name,country_id)
3)工作(ssn,job_title,salary)
[国家]
[人]
[作业]
每个国家/地区的平均值(每个国家/地区)=每个工人总工资的总和)/工人数量
国家/地区 - 平均工资
答案 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;
答案 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;
使用with子句将更具可读性和可理解性。