简体   繁体   中英

PostgreSQL for the average number of attendances of an event per month

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM