-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy path34-email-table-transformation.sql
48 lines (31 loc) · 1.6 KB
/
34-email-table-transformation.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
-- Each Facebook user can designate a personal email address, a business email address, and a recovery email address.
-- Unfortunately, the table is currently in the wrong format, so you need to transform its structure to show the following columns
-- (see example output): user id, personal email, business email, and recovery email. Sort your answer by user id in ascending order.
-- users Table:
-- Column Name Type
-- user_id integer
-- email_type varchar
-- email varchar
-- users Example Input:
-- user_id email_type email
-- 123 personal [email protected]
-- 123 business [email protected]
-- 123 recovery [email protected]
-- 234 personal [email protected]
-- 234 business [email protected]
-- Example Output:
-- user_id personal business recovery
-- Explanation
-- This task is basically just asking you to pivot/transform the shape of the data. It's all the same data as the input above, just in different format.
-- Each row will represent a single user with all three of their emails listed.
-- The first row shows User ID 123 (who may or may not be Nick Singh); their personal email is [email protected], their business email is [email protected], and so on.
SELECT user_id,
MAX(CASE WHEN email_type = 'personal' THEN email END) as personal,
MAX(CASE WHEN email_type = 'business' THEN email END) as business,
MAX(CASE WHEN email_type = 'recovery' THEN email END) as recovery
FROM users
GROUP BY 1
ORDER BY 1
-- remarks: basically had to pivot the table.