In this Leetcode Department Highest Salary problem solution, The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id. The Department table holds all departments of the company.
Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, your SQL query should return the following rows (order of rows does not matter).
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| IT | Jim | 90000 |
| Sales | Henry | 80000 |
+------------+----------+--------+
Problem solution in Oracle.
select d.Name as Department, e.NAME as Employee, e.SALARY as Salary from Employee e inner join Department d on e.DepartmentId=d.Id inner join ( select DepartmentId , max(Salary) as Salary from Employee group by DepartmentId ) a on e.Salary=a.Salary and e.DepartmentId=a.DepartmentId
Problem solution in Mysql.
SELECT d.Department, e.Name as Employee, e.Salary FROM ( SELECT d.Name AS Department, d.Id AS dId, MAX(e.Salary) AS Salary FROM Employee e LEFT JOIN Department d ON e.DepartmentID = d.Id GROUP BY Department, dId ) d INNER JOIN Employee e ON d.Salary = e.Salary AND d.dId = e.DepartmentId
Problem solution in C++.
select c.Name as Department, a.Name as Employee, a.Salary as Salary from ( select * from Employee ) a inner join ( select max(Salary) as Salary, DepartmentId from Employee group by DepartmentId ) b on a.Salary = b.Salary and a.DepartmentId = b.DepartmentId left join ( select * from Department ) c on a.DepartmentId = c.Id where c.Name is not null
0 Comments