-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion_5.sql
More file actions
54 lines (49 loc) · 1.94 KB
/
question_5.sql
File metadata and controls
54 lines (49 loc) · 1.94 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
-- question_5.sql
-- The following queries assumes that the following tables exists
-- create table organizations (
-- id uuid primary key default uuid_generate_v4() not null,
-- name text not null
-- );
--
-- create table users (
-- id uuid default uuid_generate_v4() not null,
-- name text not null,
-- age int,
-- org_id uuid references organizations(id) not null,
-- meta jsonb
-- );
-- and the meta field on users has the following data:
--
-- {
-- "joined": "2015-01-03T02:32:44",
-- "comment": "prefers linux"
-- }
-- Give me the name and age of all employees.
SELECT name, age FROM users;
-- Give me the name and organization of all employees.
SELECT users.name, organizations.name
FROM users INNER JOIN organizations
ON users.org_id = organizations.id;
-- Give me the oldest person at each organization.
WITH max_users_age_by_organization AS (
SELECT users.org_id, MAX(users.age) as age
FROM users
GROUP BY users.org_id
)
SELECT organizations.id, organizations.name, users.name, max_users_age_by_organization.age
FROM organizations
INNER JOIN max_users_age_by_organization ON organizations.id = max_users_age_by_organization.org_id
INNER JOIN users ON max_users_age_by_organization.age = users.age;
-- Find the first person who joined each company.
WITH first_joined_users_by_organization AS (
SELECT users.org_id, MIN( to_timestamp(users.meta->>'joined','YYYY-MM-DD HH:MI:SS')::timestamp ) as joined
FROM users
GROUP BY users.org_id
)
SELECT organizations.id, organizations.name, users.name, first_joined_users_by_organization.joined
FROM organizations
INNER JOIN first_joined_users_by_organization ON organizations.id = first_joined_users_by_organization.org_id
INNER JOIN users ON first_joined_users_by_organization.joined = to_timestamp(users.meta->>'joined','YYYY-MM-DD HH:MI:SS')::timestamp;
-- Give me the name and comment of all employees.
SELECT users.name, users.meta->>'comment'
FROM users;