I have a table storing activity information for my application's users.
| username | day |
|----------|-----|
| u1 | 1 |
| u1 | 2 |
| u1 | 3 |
| u2 | 2 |
| u3 | 1 |
| u3 | 4 |
I'd like to be able to get historical data regarding unique and recent users for each day.
- Unique users for day N are all the distinct users that had any activity between day 0 and day N.
- Recent users for day N are all the distinct users that had any activity on day N-1 or day N. In the actual application this will be between day N-30 and N.
I'm able to get the list of the users that were active on each specific day, but I'm not sure how I can aggregate this data to get unique or recent users.
SELECT
day,
array_agg(username) as day_users
FROM myTable
GROUP BY day
ORDER BY day;
| day | day_users |
|-----|-----------|
| 1 | u1, u3 |
| 2 | u1,u2 |
| 3 | u1 |
| 4 | u3 |
For the sample data above, the expected output would be (spacing not required):
| day | unique_users | recent_users
|-----|--------------|-------------
| 1 | u1, u3 | u1, u3
| 2 | u1,u2,u3 | u1,u2,u3
| 3 | u1,u2,u3 | u1,u2
| 4 | u1,u2,u3 | u1, u3
Relevant SQL Fiddle: http://sqlfiddle.com/#!17/b793f/1
CREATE TABLEstatement) showing data types and constraints.