Microsoft SQL Server 2008
一个工人生活在某个国家,可能有不止一份工作,拿着不止一份薪水。
我想得到每个国家个人总工资的平均值。
表格:
1) countries(country_id,name)
2) 人员(ssn,name,country_id)
3) jobs(ssn,job_title,salary)
[国家/地区]
- 1,美国
- 2、德国
[人]
- 010101,John,1
- 020202,李,1
- 030303,哈利,2岁
[jobs]
- 010101,教师,3200
- 010101,建筑商,1500
- 020202,演员,45000
- 020202,歌手,200000
- 030303,生产商,120000
所需查询结果:
每个国家的平均值(每个国家)=每个工人的总工资之和)/工人人数
国家/地区-平均工资
- 美国-124850
- 德国-120000
试试这个:
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
这应该适用于您:
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
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子句将更加可读和易懂。