List the number of employees and department numbers whose salary is higher than the average salary of the department in each department, and sort them by department number (expressed by sql statement).

Query the number of employees and department numbers whose salary is higher than the average salary of the department in each department, and sort by department number (expressed by sql statement)

1. Created table

 

2. Ideas:

(1) First query the average salary of each department

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

  -----> Query result:

(2) Use the idea of ​​​​joint query to query: select * from table1, table2 where table1.name=table2.name

        That is, perform a joint query on the Employee table and the query results in the above table to find out all records whose salary is greater than the average salary.

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; 

   ---->Query result:

 

(3) Query the number of employees and department numbers in each department whose salary is higher than the average salary of the department, and sort by department number

    

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; 

   ----->Query result:

     

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324653979&siteId=291194637