WITH first AS (SELECT u.user_id, CAST(DATE_TRUNC('month', e.event_time) as date) AS first_date FROM tools_shop.users u JOIN tools_shop.orders o ON u.user_id = o.user_id JOIN tools_shop.events e ON u.user_id = e.user_id GROUP BY u.user_id, first_date), cohort_users AS (SELECT first_date, COUNT(DISTINCT user_id) AS num_users FROM first GROUP BY first_date) SELECT first_date, num_users FROM cohort_users