Skip to content

1148. Article Views I

Problem Statement

Table: Views

Column NameType
article_idint
author_idint
viewer_idint
view_datedate

There is no primary key (column with unique values) for this table, the table may have duplicate rows.

Each row of this table indicates that some viewer viewed an article (written by some author) on some date.

Note that equal author_id and viewer_id indicate the same person.

Instructions

  • Write a solution to find all the authors that viewed at least one of their own articles.
  • Return the result table sorted by id in ascending order.
  • The result format is in the following example.

Example

Input: Views table

article_idauthor_idviewer_idview_date
1352019-08-01
1362019-08-02
2772019-08-01
2762019-08-02
4712019-07-22
3442019-07-21
3442019-07-21

Output:

id
4
7

Submissions

sql
SELECT DISTINCT author_id AS id
FROM Views
WHERE author_id = viewer_id
ORDER BY id ASC;
python
import pandas as pd

def article_views(views: pd.DataFrame) -> pd.DataFrame:
    unique_authors = views[views['author_id'] == views['viewer_id']]['author_id'].unique()
    sorted_authors = sorted(unique_authors)
    return pd.DataFrame({'id': sorted_authors})

Explanations

PostgreSQL
Submitted by @noeyislearning
  • SELECT DISTINCT author_id AS id: This part of the statement specifies the column that you want to retrieve from the database. In this case, you're retrieving the author_id column and renaming it to id using the AS keyword. The DISTINCT keyword ensures that each id in the result set is unique.
  • FROM Views: This part of the statement specifies the table from which you want to retrieve the data. Here, Views is the table.
  • WHERE author_id = viewer_id: This is a condition that filters the rows to include in the result set. It only includes rows where the author_id is the same as the viewer_id. This effectively selects the views where the author viewed their own article.
  • ORDER BY id ASC: This part sorts the result set by the id column in ascending order (ASC).
Pandas
Submitted by @noeyislearning