easyGROUP BYAggregationDuplicate handling
Active Users Per Day
Report the number of distinct active users for each date of activity.
Start practicePrompt
Active Users Per Day
Prompt
Given the activity table below, write a query that returns, for each date that has any activity, the number of distinct users who were active that day.
- A user is "active" on a day if they have at least one event row that day.
- A user with several events on the same day must be counted once.
- Output columns:
event_dateandactive_users, ordered byevent_date. activity.user_idmay beNULL; aNULLuser_id is not a user and must not be counted.
Example
| user_id | event_date | event_type |
|---|---|---|
| 1 | 2024-01-01 | view |
| 1 | 2024-01-01 | click |
| 2 | 2024-01-01 | view |
| 1 | 2024-01-02 | click |
Expected result:
| event_date | active_users |
|---|---|
| 2024-01-01 | 2 |
| 2024-01-02 | 1 |
Constraints
- The
activitytable has one row per event; a user can appear many times per day. activity.user_idis nullable.
Tips
COUNT(DISTINCT user_id)grouped byevent_dateis the whole trick —COUNT(*)would overcount.
Expected concepts
- COUNT(DISTINCT)
- GROUP BY
- Duplicate handling
Schema
CREATE TABLE activity (
user_id INTEGER, -- NULL allowed
event_date DATE NOT NULL,
event_type TEXT NOT NULL
);
Sample data
INSERT INTO activity (user_id, event_date, event_type) VALUES
(1, '2024-01-01', 'view'),
(1, '2024-01-01', 'click'),
(2, '2024-01-01', 'view'),
(1, '2024-01-02', 'click'),
(3, '2024-01-02', 'view'),
(3, '2024-01-02', 'click');
Additional hidden fixtures are applied during validation to test edge cases.