LeetCode 1148. Article Views I – SQL Query Solution

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.

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 1:

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

Solution :

SELECT DISTINCT author_id AS id
FROM Views
WHERE author_id = viewer_id
ORDER BY id;
Explanation:
 
SELECT DISTINCT author_id AS id: This part of the query selects unique author_id values from the “Views” table and renames them as id. 
We use DISTINCT to ensure that each author is only listed once in the result.
 
FROM Views: Specifies the table you are querying from, which is “Views” in this case.
 
WHERE author_id = viewer_id: This is the crucial part of the query. It filters the rows where the author_id is equal to the viewer_id. This condition ensures that we are selecting only those rows where the author viewed their own article.
 
ORDER BY id: Orders the result set by the id (which is actually the author_id with a different name) in ascending order.

More Post –

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top