[LeetCode] 1148. Article Views I - SQL

Donghyun·2024년 8월 8일
0

Code Kata - SQL

목록 보기
37/61
post-thumbnail

링크: https://leetcode.com/problems/article-views-i/

Table: Views

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| article_id    | int     |
| author_id     | int     |
| viewer_id     | int     |
| view_date     | date    |
+---------------+---------+
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_id | author_id | viewer_id | view_date  |
+------------+-----------+-----------+------------+
| 1          | 3         | 5         | 2019-08-01 |
| 1          | 3         | 6         | 2019-08-02 |
| 2          | 7         | 7         | 2019-08-01 |
| 2          | 7         | 6         | 2019-08-02 |
| 4          | 7         | 1         | 2019-07-22 |
| 3          | 4         | 4         | 2019-07-21 |
| 3          | 4         | 4         | 2019-07-21 |
+------------+-----------+-----------+------------+
Output:
+------+
| id   |
+------+
| 4    |
| 7    |
+------+

문제풀이

문제 이해하기:

자신의 기사를 하나 이상 본 모든 저자를 찾아야 함. 결과는 id 를 기준으로 오름차순으로 정렬.

최종코드

SELECT 
    DISTINCT(author_id) id
FROM Views
WHERE author_id = viewer_id
ORDER BY 1 ASC;
  • views 테이블에서
  • author_id 와 viewer_id 가 같은 즉, 자신의 기사를 본 저자에 대해
  • 중복되지 않는 author_id 를 SELECT 하고
  • 마지막으로 author_id 를 기준으로 오름차순 정렬!
profile
데이터분석 공부 일기~!

0개의 댓글