Article Views II Problem
Description
LeetCode Problem 1149.
Table: Views
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| article_id | int |
| author_id | int |
| viewer_id | int |
| view_date | date |
+---------------+---------+
There is no primary key for this table, it 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 an SQL query to find all the people who viewed more than one article on the same date, sorted in ascending order by their id.
The query result format is in the following example:
Views table:
+------------+-----------+-----------+------------+
| article_id | author_id | viewer_id | view_date |
+------------+-----------+-----------+------------+
| 1 | 3 | 5 | 2019-08-01 |
| 3 | 4 | 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 |
+------------+-----------+-----------+------------+
Result table:
+------+
| id |
+------+
| 5 |
| 6 |
+------+
Solution
Approach: GROUP BY Viewer and Date
"More than one article on the same date" is a question about each (viewer_id, view_date) pair, so group by those two columns and keep the groups with COUNT(DISTINCT article_id) > 1.
DISTINCT inside the count matters because the table can contain duplicate rows: viewer 4 viewed article 3 twice on 2019-07-21, but that is one article, not two.
A viewer can qualify on several dates, and each of those dates produces a row. SELECT DISTINCT viewer_id lists each person once. Then sort by id.
The Pandas version counts unique articles per viewer and date with groupby(...).nunique(), keeps the counts above 1, and returns the distinct viewer ids in ascending order.
SELECT DISTINCT viewer_id AS id
FROM Views
GROUP BY viewer_id, view_date
HAVING COUNT(DISTINCT article_id) > 1
ORDER BY id;