sql:查询工资低于所在部门平均工资的员工的姓名和工资

上一篇 / 下一篇  2012-03-02 16:53:00 / 个人分类:数据库

51Testing软件测试网%AD5EN {v
见过这么一道sql的题
51Testing软件测试网\-\/kU+CW2i$N
查询工资低于所在部门平均工资的员工的姓名和工资

!]w-pw!u C(~.j}^0
员工表emp(id,name,dept_id,salary,) 部门表dept(id,name)

#I!p3r*x:A5g/D @|^0

)?4RH0}%}1A0
如果聪明的你,认为你不用查度娘谷歌能正确写出来,那么恭喜你,你可以不用朝下看了

JI6_~ N.x(cK0
51Testing软件测试网 [ErHL;s!CO$\
看到有人这么写
select e.name,salary,avg(salary)
from emp e,dept d
where e.dept_id=d.id
group by e.dept_id
having salary<avg(salary)

}?6aFL i.X0
很明显写错了,其实这个语句不用查询dept表的,而且这样只是查出了比整个表平均工资小的记录,而不是所在部门的平均工资,注意这个所在部门,是关键,
51Testing软件测试网7i5\)OG/`cs
比较常用的2种写法:

!fQ ZHn+}0
1.
select a.name, a.salary from 
emp a 
where salary<(select avg(salary)from emp where a.dept_id=dept_id group by 
51Testing软件测试网xg]b t0Loou }
dept_id);
2.
select a.name,a.salary from 
emp a,
(select dept_id, avg(salary) avge from emp group by dept_id) b 
where a.salary<avge and a.dept_id=b.dept_id;
51Testing软件测试网1~P'Y/OC z d&r5P
如果是oracle,还可以使用partition by
select * from
(select a.name,a.salary,avg(a.salary) over (PARTITION BY dept_id) as Average from 
51Testing软件测试网uu|1};~
emp a)
where salary < Average
51Testing软件测试网Ic0]3G+X
这篇帖子介绍了其他分析函数使用partition by的情形,很详细,值得一看
http://hi.baidu.com/wangzhiqing999/blog/item/f4a845660a5352cbe7113a88.html

TAG:

 

评分:0

我来说两句

Open Toolbar