|
| 1 | +# Time: O(n^2) |
| 2 | +# Space: O(n) |
| 3 | +# |
| 4 | +# The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id. |
| 5 | +# |
| 6 | +# +----+-------+--------+--------------+ |
| 7 | +# | Id | Name | Salary | DepartmentId | |
| 8 | +# +----+-------+--------+--------------+ |
| 9 | +# | 1 | Joe | 70000 | 1 | |
| 10 | +# | 2 | Henry | 80000 | 2 | |
| 11 | +# | 3 | Sam | 60000 | 2 | |
| 12 | +# | 4 | Max | 90000 | 1 | |
| 13 | +# | 5 | Janet | 69000 | 1 | |
| 14 | +# | 6 | Randy | 85000 | 1 | |
| 15 | +# +----+-------+--------+--------------+ |
| 16 | +# The Department table holds all departments of the company. |
| 17 | +# |
| 18 | +# +----+----------+ |
| 19 | +# | Id | Name | |
| 20 | +# +----+----------+ |
| 21 | +# | 1 | IT | |
| 22 | +# | 2 | Sales | |
| 23 | +# +----+----------+ |
| 24 | +# Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows. |
| 25 | +# |
| 26 | +# +------------+----------+--------+ |
| 27 | +# | Department | Employee | Salary | |
| 28 | +# +------------+----------+--------+ |
| 29 | +# | IT | Max | 90000 | |
| 30 | +# | IT | Randy | 85000 | |
| 31 | +# | IT | Joe | 70000 | |
| 32 | +# | Sales | Henry | 80000 | |
| 33 | +# | Sales | Sam | 60000 | |
| 34 | +# +------------+----------+--------+ |
| 35 | + |
| 36 | +# Write your MySQL query statement below |
| 37 | +SELECT D.Name AS Department, E.Name AS Employee, E.Salary AS Salary |
| 38 | +FROM Employee E INNER JOIN Department D ON E.DepartmentId = D.Id |
| 39 | +WHERE (SELECT COUNT(DISTINCT(Salary)) FROM Employee |
| 40 | + WHERE DepartmentId = E.DepartmentId AND Salary > E.Salary) < 3 |
| 41 | +ORDER by E.DepartmentId, E.Salary DESC; |
0 commit comments