|
7 | 7 | import psycopg2
|
8 | 8 |
|
9 | 9 | def main():
|
| 10 | + # Connect to an existing database |
| 11 | + conn = psycopg2.connect("dbname=news") |
| 12 | + |
| 13 | + # Open a cursor to perform database operations |
| 14 | + cur = conn.cursor() |
10 | 15 |
|
| 16 | + # Question 1 |
11 | 17 | sql_popular_articles = """
|
12 |
| - SELECT * |
| 18 | + SELECT article_view.title, article_view.view |
13 | 19 | FROM article_view
|
14 | 20 | ORDER BY article_view.view DESC
|
15 | 21 | LIMIT 3;
|
16 | 22 | """
|
| 23 | + cur.execute(sql_popular_articles) |
| 24 | + print("Most popular articles:") |
| 25 | + for (title, view) in cur.fetchall(): |
| 26 | + print(" {} - {} views".format(title, view)) |
| 27 | + print("-" * 70) |
17 | 28 |
|
| 29 | + |
| 30 | + # Question 2 |
18 | 31 | sql_popular_authors = """
|
19 | 32 | SELECT article_view.name, SUM(article_view.view) AS author_view
|
20 | 33 | FROM article_view
|
21 | 34 | GROUP BY article_view.name
|
22 | 35 | ORDER BY author_view DESC
|
23 | 36 | LIMIT 1;
|
24 | 37 | """
|
| 38 | + cur.execute(sql_popular_authors) |
| 39 | + print("Most popular authors:") |
| 40 | + for (name, view) in cur.fetchall(): |
| 41 | + print(" {} - {} views".format(name, view)) |
| 42 | + print("-" * 70) |
25 | 43 |
|
| 44 | + # Question 3 |
26 | 45 | sql_more_than_one_percent_errors = """
|
27 | 46 | SELECT *
|
28 | 47 | FROM error_rate
|
29 | 48 | WHERE error_rate.percentage > 1
|
30 | 49 | ORDER BY error_rate.percentage DESC;
|
31 | 50 | """
|
32 |
| - |
33 |
| - # Connect to an existing database |
34 |
| - conn = psycopg2.connect("dbname=news") |
35 |
| - |
36 |
| - # Open a cursor to perform database operations |
37 |
| - cur = conn.cursor() |
38 |
| - |
39 |
| - |
| 51 | + cur.execute(sql_more_than_one_percent_errors) |
| 52 | + print("Days with more than 1% errors:") |
| 53 | + for (date, percentage) in cur.fetchall(): |
| 54 | + print(" {} - {}% errors".format(date, percentage)) |
| 55 | + print("-" * 70) |
40 | 56 |
|
41 | 57 |
|
42 |
| - |
43 |
| - |
44 |
| - |
45 |
| - |
46 |
| - |
47 | 58 | # Close communication with the database
|
48 | 59 | cur.close()
|
49 | 60 | conn.close()
|
|
0 commit comments