1
+ -- Question 55
2
+ -- Table: Employees
3
+
4
+ -- +---------------+---------+
5
+ -- | Column Name | Type |
6
+ -- +---------------+---------+
7
+ -- | employee_id | int |
8
+ -- | employee_name | varchar |
9
+ -- | manager_id | int |
10
+ -- +---------------+---------+
11
+ -- employee_id is the primary key for this table.
12
+ -- Each row of this table indicates that the employee with ID employee_id and name employee_name reports his
13
+ -- work to his/her direct manager with manager_id
14
+ -- The head of the company is the employee with employee_id = 1.
15
+
16
+
17
+ -- Write an SQL query to find employee_id of all employees that directly or indirectly report their work to the head of the company.
18
+
19
+ -- The indirect relation between managers will not exceed 3 managers as the company is small.
20
+
21
+ -- Return result table in any order without duplicates.
22
+
23
+ -- The query result format is in the following example:
24
+
25
+ -- Employees table:
26
+ -- +-------------+---------------+------------+
27
+ -- | employee_id | employee_name | manager_id |
28
+ -- +-------------+---------------+------------+
29
+ -- | 1 | Boss | 1 |
30
+ -- | 3 | Alice | 3 |
31
+ -- | 2 | Bob | 1 |
32
+ -- | 4 | Daniel | 2 |
33
+ -- | 7 | Luis | 4 |
34
+ -- | 8 | Jhon | 3 |
35
+ -- | 9 | Angela | 8 |
36
+ -- | 77 | Robert | 1 |
37
+ -- +-------------+---------------+------------+
38
+
39
+ -- Result table:
40
+ -- +-------------+
41
+ -- | employee_id |
42
+ -- +-------------+
43
+ -- | 2 |
44
+ -- | 77 |
45
+ -- | 4 |
46
+ -- | 7 |
47
+ -- +-------------+
48
+
49
+ -- The head of the company is the employee with employee_id 1.
50
+ -- The employees with employee_id 2 and 77 report their work directly to the head of the company.
51
+ -- The employee with employee_id 4 report his work indirectly to the head of the company 4 --> 2 --> 1.
52
+ -- The employee with employee_id 7 report his work indirectly to the head of the company 7 --> 4 --> 2 --> 1.
53
+ -- The employees with employee_id 3, 8 and 9 don't report their work to head of company directly or indirectly.
54
+
55
+ -- Solution
56
+ select employee_id
57
+ from employees
58
+ where manager_id = 1 and employee_id != 1
59
+ union
60
+ select employee_id
61
+ from employees
62
+ where manager_id = any (select employee_id
63
+ from employees
64
+ where manager_id = 1 and employee_id != 1 )
65
+ union
66
+ select employee_id
67
+ from employees
68
+ where manager_id = any (select employee_id
69
+ from employees
70
+ where manager_id = any (select employee_id
71
+ from employees
72
+ where manager_id = 1 and employee_id != 1 ))
0 commit comments