-
Notifications
You must be signed in to change notification settings - Fork 0
/
47AdvancedQueries2.sql
94 lines (84 loc) · 2.3 KB
/
47AdvancedQueries2.sql
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
drop table if exists emp_manager;
CREATE TABLE emp_manager (
emp_no INT(11) NOT NULL,
dept_no CHAR(4) NULL,
manager_no INT(11) NOT NULL
);
insert into emp_manager
SELECT
A.*
FROM
(SELECT
e.emp_no AS employee_id,
MIN(d.dept_no) AS dept_code, #We couldn't have used DISTINCT instead of MIN() because it is not possible as it will return all the distinct department numbers and we want just one of all for each employee.
(SELECT
e.emp_no
FROM
employees e
WHERE
emp_no = 110022) AS manager_id
FROM
employees e
JOIN dept_emp d ON e.emp_no = d.emp_no
WHERE
e.emp_no <= 10020
GROUP BY e.emp_no
ORDER BY e.emp_no) AS A
UNION SELECT
B.*
FROM
(SELECT
e.emp_no AS employee_id,
MIN(d.dept_no) AS dept_code,
(SELECT
e.emp_no
FROM
employees e
WHERE
emp_no = 110039) AS manager_id
FROM
employees e
JOIN dept_emp d ON e.emp_no = d.emp_no
WHERE
e.emp_no BETWEEN 10021 AND 10040
GROUP BY e.emp_no
ORDER BY e.emp_no) AS B
union
SELECT
C.*
FROM
(SELECT
e.emp_no AS employee_id,
MIN(d.dept_no) AS dept_code,#We couldn't have used DISTINCT instead of MIN() because it is not possible as it will return all the distinct department numbers and we want just one of all for each employee.
(SELECT
e.emp_no
FROM
employees e
WHERE
emp_no = 110022) AS manager_id
FROM
employees e
JOIN dept_emp d ON e.emp_no = d.emp_no
WHERE
e.emp_no=110039
GROUP BY e.emp_no
ORDER BY e.emp_no) AS C
UNION SELECT
D.*
FROM
(SELECT
e.emp_no AS employee_id,
MIN(d.dept_no) AS dept_code,
(SELECT
e.emp_no
FROM
employees e
WHERE
emp_no = 110039) AS manager_id
FROM
employees e
JOIN dept_emp d ON e.emp_no = d.emp_no
WHERE
e.emp_no=110022
GROUP BY e.emp_no
ORDER BY e.emp_no) AS D;