-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0185-Department_Top_Three_Salaries.sql
More file actions
66 lines (65 loc) · 2.06 KB
/
0185-Department_Top_Three_Salaries.sql
File metadata and controls
66 lines (65 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*******************************************************************************
* 0185-Department_Top_Three_Salaries.sql
* Billy.Ljm
* 19 July 2025
*
* =======
* Problem
* =======
* https://leetcode.com/problems/department-top-three-salaries/
*
* Table: Employee
* +--------------+---------+
* | Column Name | Type |
* +--------------+---------+
* | id | int |
* | name | varchar |
* | salary | int |
* | departmentId | int |
* +--------------+---------+
* id is the primary key (column with unique values) for this table.
* departmentId is a foreign key (reference column) of the ID from the
* Department table.
* Each row of this table indicates the ID, name, and salary of an employee. It
* also contains the ID of their department.
*
* Table: Department
* +-------------+---------+
* | Column Name | Type |
* +-------------+---------+
* | id | int |
* | name | varchar |
* +-------------+---------+
* id is the primary key (column with unique values) for this table.
* Each row of this table indicates the ID of a department and its name.
*
* A company's executives are interested in seeing who earns the most money in
* each of the company's departments. A high earner in a department is an
* employee who has a salary in the top three unique salaries for that
* department.
*
* Write a solution to find the employees who are high earners in each of the
* departments.
*
* Return the result table in any order.
*
* ===========
* My Approach
* ===========
* We use `DENSE RANK` and `PARTITION BY` to pick out the employees with the
* highest salaries in each department.
******************************************************************************/
SELECT
Department.name AS Department,
Employee.name AS Employee,
Employee.salary AS Salary
FROM (
SELECT *, DENSE_RANK() OVER (
PARTITION BY departmentId
ORDER BY salary DESC
) AS rankk
FROM Employee
) AS Employee
LEFT JOIN Department
ON Employee.departmentID = Department.id
WHERE Employee.rankk <= 3