User Activity for the Past 30 Days I
Task: Find the daily active user count for a period of 30 days ending 2019-07-27 inclusive. A user was active on someday if they made at least one activity on that day.
Table: Activity
+---------------+-------------+
| Column Name | Type |
+---------------+-------------+
| user_id | INT |
| session_id | INT |
| activity_date | date |
| activity_type | varchar(20) |
+---------------+-------------+
Input: 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 |
+---------+------------+---------------+---------------+
Output:
+------------+--------------+
| day | active_users |
+------------+--------------+
| 2019-07-20 | 2 |
| 2019-07-21 | 2 |
+------------+--------------+ View Reference Solution & Explanation ▼
This solution uses the `GROUP BY` clause to aggregate results to find the required output.
SELECT activity_date AS day, COUNT(DISTINCT user_id) AS active_users FROM Activity WHERE activity_date BETWEEN '2019-06-28' AND '2019-07-27' GROUP BY activity_date;