列出各个部门中工资高于本部门的平均工资的员工数和部门号,并按部门号排序(用sql语句来表达)。

时间:2018-04-22 19:58:52   收藏:0   阅读:1110

查询出各个部门中工资高于本部门的平均工资的员工数和部门号,并按部门号排序(用sql语句来表达)

1.创建的表格

技术分享图片

 

2.思路:

(1)首先查询各个部门的平均工资

1 select deptid ,avg(salary) as avg_salary from Employee group by deptid; 

  -----> 查询结果:

技术分享图片

(2)利用联合查询的思想进行查询:select * from table1,table2 where table1.name=table2.name

        即把Employee表与上表查询出的结果进行联合查询,找出所有工资大于平均工资的记录。

1 select table1.* from Employee as table1,
2 (select deptid ,avg(salary) as avg_salary from Employee group by deptid) as table2
3 where table1.deptid=table2.deptid and table1.salary>table2.avg_salary; 

   ---->查询结果:

技术分享图片

 

(3)查询出各个部门中工资高于本部门的平均工资的员工数和部门号,并按部门号排序

    

1 select table1.deptid,count(*) from Employee as table1,
2 (select deptid ,avg(salary) as avg_salary from Employee group by deptid) as table2
3 where table1.deptid=table2.deptid and table1.salary>table2.avg_salary
4 group by table1.deptid order by table1.deptid; 

   ----->查询结果:

     技术分享图片

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!