Reputation: 7702
I'm trying to write some SQL to understand the average number of events attended, per month.
Attendees
| id | user_id | event_id | created_at |
I've tried:
SELECT AVG(b.rcount) FROM (select count(*) as rcount FROM attendees GROUP BY attendees.user_id) as b;
But this returns 5.77 (which is just the average of all time). I'm trying to get the average per month.
The results would ideally be:
2020-01-01, 2.1
2020-01-02, 2.4
2020-01-03, 3.3
...
I also tried this:
SELECT mnth, AVG(b.rcount) FROM (select date_trunc('month', created_at) as mnth, count(*) as rcount FROM attendees GROUP BY 1, 2) as b;
But got: ERROR: aggregate functions are not allowed in GROUP BY
Upvotes: 0
Views: 59
Reputation: 222442
If I follow you correctly, a simple approach is to divide the number of rows per month by the count of distinct users:
select
date_trunc('month', created_at) created_month,
1.0 * count(*) / count(distinct user_id) avg_events_per_user
from attendees
group by date_trunc('month', created_at)
Upvotes: 1