查看: 1820|回复: 0
打印 上一主题 下一主题
收起左侧

[数据库部分] 182、列出各个部门中工资高于本部门的平均工资的员工数和部门号,并按部门号排序

[复制链接]

566

主题

713

帖子

3827

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
3827
楼主
跳转到指定楼层
发表于 2016-9-8 17:55:10 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
182、列出各个部门中工资高于本部门的平均工资的员工数和部门号,并按部门号排序

创建表:

mysql> create table employee921(id int primary key auto_increment,name varchar(5

0),salary bigint,deptid int);

 

插入实验数据:

mysql> insert into employee921 values(null,'zs',1000,1),(null,'ls',1100,1),(null

,'ww',1100,1),(null,'zl',900,1) ,(null,'zl',1000,2), (null,'zl',900,2) ,(null,'z

l',1000,2) , (null,'zl',1100,2);

 

编写sql语句:

 

()select avg(salary) from employee921 group by deptid;

()mysql> select employee921.id,employee921.name,employee921.salary,employee921.dep

tid tid from  employee921 where salary > (select avg(salary) from employee921 where  deptid = tid);

效率低的一个语句,仅供学习参考使用(在group by之后不能使用where,只能使用having,在group by之前可以使用where,即表示对过滤后的结果分组):

mysql> select employee921.id,employee921.name,employee921.salary,employee921.dep

tid tid from  employee921 where salary > (select avg(salary) from employee921 group by deptid having deptid = tid);

()select count(*) ,tid

from (

select employee921.id,employee921.name,employee921.salary,employee921.deptid tid

from        employee921

where salary >

(select avg(salary) from employee921 where  deptid = tid)

) as t

group by tid ;

 

另外一种方式:关联查询

select a.ename,a.salary,a.deptid

from emp a,

(select deptd,avg(salary) avgsal from emp group by deptid ) b

where a.deptid=b.deptid and a.salary>b.avgsal


来自安卓客户端来自安卓客户端
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

  • 打开微信扫一扫