|
| 1 | +# Time: O(n^2) |
| 2 | +# Space: O(n) |
| 3 | +# |
| 4 | +# The Employee table holds all employees. Every employee has an Id, a salary, 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 | +# +----+-------+--------+--------------+ |
| 14 | +# The Department table holds all departments of the company. |
| 15 | +# |
| 16 | +# +----+----------+ |
| 17 | +# | Id | Name | |
| 18 | +# +----+----------+ |
| 19 | +# | 1 | IT | |
| 20 | +# | 2 | Sales | |
| 21 | +# +----+----------+ |
| 22 | +# Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, Max has the highest salary in the IT department and Henry has the highest salary in the Sales department. |
| 23 | +# |
| 24 | +# +------------+----------+--------+ |
| 25 | +# | Department | Employee | Salary | |
| 26 | +# +------------+----------+--------+ |
| 27 | +# | IT | Max | 90000 | |
| 28 | +# | Sales | Henry | 80000 | |
| 29 | +# +------------+----------+--------+ |
| 30 | +# |
| 31 | +# Write your MySQL query statement below |
| 32 | +SELECT d.Department AS Department, e.Name AS Employee, d.Salary AS Salary |
| 33 | +FROM (SELECT Department.Id AS DepartmentId, Department.Name AS Department, emp.Salary AS Salary |
| 34 | + FROM Department JOIN (SELECT DepartmentId, MAX(Salary) AS Salary FROM Employee GROUP BY Employee.DepartmentId) emp |
| 35 | + ON Department.Id = emp.DepartmentId) d |
| 36 | + JOIN Employee e |
| 37 | + ON e.DepartmentId = d.DepartmentId and e.Salary = d.Salary |
| 38 | + |
| 39 | +# Write your MySQL query statement below |
| 40 | +SELECT Department.Name AS Department, Employee.Name AS Employee, Employee.Salary AS Salary |
| 41 | +FROM Department JOIN Employee ON Employee.DepartmentId = Department.Id |
| 42 | +WHERE Employee.Salary IN (SELECT MAX(e.Salary) FROM Employee e WHERE e.DepartmentId = Employee.DepartmentId) |
0 commit comments