面试题:查询部门工资排前三的员工信息
难度:难
表Employee:
1 +----+-------+--------+--------------+ 2 | Id | Name | Salary | DepartmentId | 3 +----+-------+--------+--------------+ 4 | 1 | Joe | 70000 | 1 | 5 | 2 | Henry | 80000 | 2 | 6 | 3 | Sam | 60000 | 2 | 7 | 4 | Max | 90000 | 1 | 8 | 5 | Janet | 69000 | 1 | 9 | 6 | Randy | 85000 | 1 | 10 +----+-------+--------+--------------+
表Department:
1 +----+----------+ 2 | Id | Name | 3 +----+----------+ 4 | 1 | IT | 5 | 2 | Sales | 6 +----+----------+
写一段SQL查询各部门收入前三位的员工信息,返回结果如下:
1 +------------+----------+--------+ 2 | Department | Employee | Salary | 3 +------------+----------+--------+ 4 | IT | Max | 90000 | 5 | IT | Randy | 85000 | 6 | IT | Joe | 70000 | 7 | Sales | Henry | 80000 | 8 | Sales | Sam | 60000 | 9 +------------+----------+--------+
答案:
1 Select a.Name as Department, b.Name as Employee, b.Salary 2 from Department a, Employee b 3 where b.DepartmentId = a.Id and ( 4 Select count(distinct Salary) From Employee where DepartmentId=a.Id and Salary > b.Salary 5 )<3 6 order by Department