1
+ /*
2
+ Table: Views
3
+
4
+ +---------------+---------+
5
+ | Column Name | Type |
6
+ +---------------+---------+
7
+ | article_id | int |
8
+ | author_id | int |
9
+ | viewer_id | int |
10
+ | view_date | date |
11
+ +---------------+---------+
12
+ There is no primary key for this table, it may have duplicate rows.
13
+ Each row of this table indicates that some viewer viewed an article (written by some author) on some date.
14
+ Note that equal author_id and viewer_id indicate the same person.
15
+
16
+
17
+ Required Query:
18
+
19
+ 1) Find all the authors that viewed at least one of their own articles.
20
+
21
+ 2) Return the result table sorted by id in ascending order.
22
+
23
+
24
+ SQL Schema:
25
+
26
+ Create table If Not Exists Views (article_id int, author_id int, viewer_id int, view_date date)
27
+ Truncate table Views
28
+ insert into Views (article_id, author_id, viewer_id, view_date) values ('1', '3', '5', '2019-08-01')
29
+ insert into Views (article_id, author_id, viewer_id, view_date) values ('1', '3', '6', '2019-08-02')
30
+ insert into Views (article_id, author_id, viewer_id, view_date) values ('2', '7', '7', '2019-08-01')
31
+ insert into Views (article_id, author_id, viewer_id, view_date) values ('2', '7', '6', '2019-08-02')
32
+ insert into Views (article_id, author_id, viewer_id, view_date) values ('4', '7', '1', '2019-07-22')
33
+ insert into Views (article_id, author_id, viewer_id, view_date) values ('3', '4', '4', '2019-07-21')
34
+ insert into Views (article_id, author_id, viewer_id, view_date) values ('3', '4', '4', '2019-07-21')
35
+
36
+ Example:
37
+
38
+ Input:
39
+ Views table:
40
+ +------------+-----------+-----------+------------+
41
+ | article_id | author_id | viewer_id | view_date |
42
+ +------------+-----------+-----------+------------+
43
+ | 1 | 3 | 5 | 2019-08-01 |
44
+ | 1 | 3 | 6 | 2019-08-02 |
45
+ | 2 | 7 | 7 | 2019-08-01 |
46
+ | 2 | 7 | 6 | 2019-08-02 |
47
+ | 4 | 7 | 1 | 2019-07-22 |
48
+ | 3 | 4 | 4 | 2019-07-21 |
49
+ | 3 | 4 | 4 | 2019-07-21 |
50
+ +------------+-----------+-----------+------------+
51
+ Output:
52
+ +------+
53
+ | id |
54
+ +------+
55
+ | 4 |
56
+ | 7 |
57
+ +------+
58
+ */
59
+
60
+ -- Solution:
61
+ SELECT DISTINCT (author_id) AS id
62
+ FROM Views
63
+ WHERE author_id = viewer_id
64
+ ORDER BY author_id
0 commit comments