Skip to content

Commit 6335b5e

Browse files
authored
Create 12. .py
1 parent 01f1c8c commit 6335b5e

File tree

1 file changed

+59
-0
lines changed
  • Introduction to Relational Databases in SQL/4. Glue together tables with foreign keys

1 file changed

+59
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
Join all the tables together
3+
In this last exercise, your task is to find the university city of the professor with the most affiliations in the sector "Media & communication".
4+
5+
For this,
6+
7+
you need to join all the tables,
8+
group by some column,
9+
and then use selection criteria to get only the rows in the correct sector.
10+
Let's do this in three steps!
11+
12+
Instructions 3/3
13+
14+
- Join all tables in the database (starting with affiliations, professors, organizations, and universities) and look at the result.
15+
- Now group the result by organization sector, professor, and university city.
16+
Count the resulting number of rows.
17+
- Only retain rows with "Media & communication" as organization sector, and sort the table by count, in descending order.
18+
19+
"""
20+
#1
21+
#-- Join all tables
22+
SELECT *
23+
FROM affiliations
24+
JOIN professors
25+
ON affiliations.professor_id = professors.id
26+
JOIN organizations
27+
ON affiliations.organization_id = organizations.id
28+
JOIN universities
29+
ON professors.university_id = universities.id;
30+
31+
#2
32+
#-- Group the table by organization sector, professor ID and university city
33+
SELECT COUNT(*), organizations.organization_sector,
34+
professors.id, universities.university_city
35+
FROM affiliations
36+
JOIN professors
37+
ON affiliations.professor_id = professors.id
38+
JOIN organizations
39+
ON affiliations.organization_id = organizations.id
40+
JOIN universities
41+
ON professors.university_id = universities.id
42+
GROUP BY organizations.organization_sector,
43+
professors.id, universities.university_city;
44+
45+
#3
46+
#-- Filter the table and sort it
47+
SELECT COUNT(*), organizations.organization_sector,
48+
professors.id, universities.university_city
49+
FROM affiliations
50+
JOIN professors
51+
ON affiliations.professor_id = professors.id
52+
JOIN organizations
53+
ON affiliations.organization_id = organizations.id
54+
JOIN universities
55+
ON professors.university_id = universities.id
56+
WHERE organizations.organization_sector = 'Media & communication'
57+
GROUP BY organizations.organization_sector,
58+
professors.id, universities.university_city
59+
ORDER BY count DESC;

0 commit comments

Comments
 (0)