找出各部门中工资高于本部门的平均工资的员工数和部门号,并按部门号排序

两张表
Employee(eid, ename, salary, deptid)
Department (deptid, depatname)

思路:

  1. 首先找出各个部门的平均工资
SELECT deptid, AVG(salary) avg_sal
FROM Employee
GROUP BY deptid
  1. 连接两表找出高于本部门的平均工资的员工数和部门号,排序
SELECT count(*), e.deptid
FROM Employee e, (SELECT deptid, AVG(salary) avg_sal FROM Employee GROUP BY deptid) avg
WHERE e.deptid = avg.deptid AND e.salary < avg.avg_sal
GROUP BY e.deptid
ORDER BY e.deptid

你可能感兴趣的:(SQL)