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

查询出各个部门中工资高于本部门的平均工资的员工数和部门号,并按部门号排序(用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; 

   ----->查询结果:

     

猜你喜欢

转载自www.cnblogs.com/pj00/p/8908449.html