-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path3. Amazon SQL Interview Question for Data Analyst Position [2-3 Year Of Experience ].sql
More file actions
102 lines (96 loc) · 1.85 KB
/
3. Amazon SQL Interview Question for Data Analyst Position [2-3 Year Of Experience ].sql
File metadata and controls
102 lines (96 loc) · 1.85 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
-- Script:
CREATE TABLE hospital (
emp_id INT,
action VARCHAR(10),
time DATETIME
);
INSERT INTO hospital VALUES
('1', 'in', '2019-12-22 09:00:00')
,('1', 'out', '2019-12-22 09:15:00')
,('2', 'in', '2019-12-22 09:00:00')
,('2', 'out', '2019-12-22 09:15:00')
,('2', 'in', '2019-12-22 09:30:00')
,('3', 'out', '2019-12-22 09:00:00')
,('3', 'in', '2019-12-22 09:15:00')
,('3', 'out', '2019-12-22 09:30:00')
,('3', 'in', '2019-12-22 09:45:00')
,('4', 'in', '2019-12-22 09:45:00')
,('5', 'out', '2019-12-22 09:40:00')
SELECT * FROM hospital;
-- Question: Write a sql to find the total number of people present inside the hospital
-- Method 1: Having
WITH cte AS (
SELECT
emp_id,
MAX(CASE WHEN action = 'in' THEN time END) AS intime,
MAX(CASE WHEN action = 'out' THEN time END) AS outtime
FROM
hospital
GROUP BY
emp_id
)
SELECT
COUNT(emp_id) AS No_of_people_presents
FROM
cte
WHERE
intime > outtime
OR outtime IS NULL;
-- Method 2: Joins
WITH intime AS(
SELECT
emp_id,
MAX(time) AS latest_in_time
FROM
hospital
WHERE
action = 'in'
GROUP BY
emp_id
),
outtime AS (
SELECT
emp_id,
MAX(time) AS latest_out_time
FROM
hospital
WHERE
action = 'out'
GROUP BY
emp_id
)
SELECT
COUNT(1)
FROM
intime
LEFT JOIN outtime ON intime.emp_id = outtime.emp_id
WHERE
latest_in_time > latest_out_time
OR latest_out_time IS NULL;
-- Method 3:
WITH latest_time AS (
SELECT
emp_id,
MAX(time) AS max_latest_time
FROM
hospital
GROUP BY
emp_id
),
latest_in_time AS (
SELECT
emp_id,
MAX(time) AS max_latest_in_time
FROM
hospital
WHERE
action = 'in'
GROUP BY
emp_id
)
SELECT
COUNT(1)
FROM
latest_time lt
INNER JOIN latest_in_time lit ON lt.emp_id = lit.emp_id
AND max_latest_time = max_latest_in_time;