User Activity For The Past 30 Days I Problem
#1141
Description
LeetCode Problem 1141.
Table: Activity
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| user_id | int |
| session_id | int |
| activity_date | date |
| activity_type | enum |
+---------------+---------+
There is no primary key for this table, it may have duplicate rows.
The activity_type column is an ENUM of type ('open_session', 'end_session', 'scroll_down', 'send_message').
The table shows the user activities for a social media website.
Note that each session belongs to exactly one user.
Write an SQL query to find the daily active user count for a period of 30 days ending 2019-07-27 inclusively. A user was active on some day if he/she made at least one activity on that day.
The query result format is in the following example:
Activity table:
+---------+------------+---------------+---------------+
| user_id | session_id | activity_date | activity_type |
+---------+------------+---------------+---------------+
| 1 | 1 | 2019-07-20 | open_session |
| 1 | 1 | 2019-07-20 | scroll_down |
| 1 | 1 | 2019-07-20 | end_session |
| 2 | 4 | 2019-07-20 | open_session |
| 2 | 4 | 2019-07-21 | send_message |
| 2 | 4 | 2019-07-21 | end_session |
| 3 | 2 | 2019-07-21 | open_session |
| 3 | 2 | 2019-07-21 | send_message |
| 3 | 2 | 2019-07-21 | end_session |
| 4 | 3 | 2019-06-25 | open_session |
| 4 | 3 | 2019-06-25 | end_session |
+---------+------------+---------------+---------------+
Result table:
+------------+--------------+
| day | active_users |
+------------+--------------+
| 2019-07-20 | 2 |
| 2019-07-21 | 2 |
+------------+--------------+
Note that we do not care about days with zero active users.
Solution
Approach: Date Range and COUNT DISTINCT
For each day in the period we count the users who did anything that day.
- The period. 30 days ending 2019-07-27 inclusive means 2019-06-28 through 2019-07-27: the end day plus the 29 days before it.
BETWEEN '2019-07-27' - INTERVAL 29 DAY AND '2019-07-27'includes both ends. Subtracting 30 days would add a 31st day (2019-06-27), and leaving out the upper bound would let later days in. - Group by day.
GROUP BY activity_date. - Count users, not rows. A user usually has several activities on the same day (open, scroll, end), so use
COUNT(DISTINCT user_id).
Days with no activity have no rows, so they don't appear, which is what the problem wants.
The Pandas version filters activity_date with between(start, end) (inclusive on both ends) and counts unique user_ids per day with nunique.
SELECT activity_date AS day,
COUNT(DISTINCT user_id) AS active_users
FROM Activity
-- 30 days ending 2019-07-27, both ends included: 2019-06-28 .. 2019-07-27.
WHERE activity_date BETWEEN '2019-07-27' - INTERVAL 29 DAY AND '2019-07-27'
GROUP BY activity_date;