This repository was archived by the owner on Apr 6, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path185.sql
More file actions
61 lines (47 loc) · 1.63 KB
/
Copy path185.sql
File metadata and controls
61 lines (47 loc) · 1.63 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
USE leetcode;
# Tables: Employee, Department
CREATE TABLE IF NOT EXISTS Employee
(
id INT,
name VARCHAR(255),
salary INT,
departmentId INT
);
CREATE TABLE IF NOT EXISTS Department
(
id INT,
name VARCHAR(255)
);
TRUNCATE TABLE Employee;
INSERT INTO Employee (id, name, salary, departmentId)
VALUES ('1', 'Joe', '85000', '1');
INSERT INTO Employee (id, name, salary, departmentId)
VALUES ('2', 'Henry', '80000', '2');
INSERT INTO Employee (id, name, salary, departmentId)
VALUES ('3', 'Sam', '60000', '2');
INSERT INTO Employee (id, name, salary, departmentId)
VALUES ('4', 'Max', '90000', '1');
INSERT INTO Employee (id, name, salary, departmentId)
VALUES ('5', 'Janet', '69000', '1');
INSERT INTO Employee (id, name, salary, departmentId)
VALUES ('6', 'Randy', '85000', '1');
INSERT INTO Employee (id, name, salary, departmentId)
VALUES ('7', 'Will', '70000', '1');
TRUNCATE TABLE Department;
INSERT INTO Department (id, name)
VALUES ('1', 'IT');
INSERT INTO Department (id, name)
VALUES ('2', 'Sales');
# Solution
WITH employee_department AS
(SELECT d.id,
d.name AS Department,
salary AS Salary,
e.name AS Employee,
DENSE_RANK() OVER (PARTITION BY d.id ORDER BY salary DESC) AS rnk
FROM Department d
JOIN Employee e
ON d.id = e.departmentId)
SELECT Department, Employee, Salary
FROM employee_department
WHERE rnk <= 3;