Similar Problems

Similar Problems not available

Department Top Three Salaries - Leetcode Solution

Companies:

  • microsoft

LeetCode:  Department Top Three Salaries Leetcode Solution

Difficulty: Hard

Topics: database  

The problem "Department Top Three Salaries" on Leetcode requires us to write an SQL query to find the top three highest salaries in each department.

To solve this problem, we need to join two tables: the "Employee" table and the "Department" table. The "Employee" table contains information about each employee, such as their name, salary, and department ID. The "Department" table contains information about each department, including its name and ID.

We can use the following SQL query to find the top three highest salaries in each department:

SELECT d.Name AS Department, e.Name AS Employee, e.Salary
FROM Employee e
JOIN Department d ON e.DepartmentId = d.Id
WHERE (
    SELECT COUNT(DISTINCT Salary)
    FROM Employee e2
    WHERE e2.Salary > e.Salary AND e.DepartmentId = e2.DepartmentId
) < 3
ORDER BY Department, Salary DESC;

The query starts by joining the "Employee" and "Department" tables on the "DepartmentId" column.

Then, it uses a subquery to count the number of unique salaries in the same department that are higher than the current employee's salary. If the count is less than 3, it means that the current employee has one of the top three highest salaries in their department.

Finally, the query sorts the results by department name and salary in descending order.

This SQL query will return a table showing the department name, employee name, and salary for the top three highest salaries in each department.

Department Top Three Salaries Solution Code

1