Question
Table name: 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.
Explaination
We have two tasks:
- Authors viewed their own articles →
WHERE author_id = viewer_id
- Sort table by id in ascending order →
ORDER BY author_id ASC
SQL ORDER BY
ORDER BY <column1>, <column2>, ... ASC|DESC;
By default, ORDER BY
sort rows in ascending order.
And if there are multiple columns, sort the rows according to the first column, and then the second column when the rows contain same values in the first column and so on.
Solution
SELECT distinct author_id AS id
FROM Views
WHERE author_id = viewer_id
ORDER BY author_id ASC
More SQL 50 questions: here
Please cite the source for reprints, feel free to verify the sources cited in the article, and point out any errors or lack of clarity of expression. You can comment in the comments section below or email to GreenMeeple@yahoo.com