Skip to content

Instantly share code, notes, and snippets.

@danielgranat
Forked from arikfr/cohort.sql
Last active March 6, 2017 20:54
Show Gist options
  • Save danielgranat/92ceca67b43994f7c5f3fce7bdb312a7 to your computer and use it in GitHub Desktop.
Save danielgranat/92ceca67b43994f7c5f3fce7bdb312a7 to your computer and use it in GitHub Desktop.
Cohort Query Example
with
time_frame as (
select current_date - 14
),
population as (
select created_at::date as cohort_date, id as unique_id
from organizations
where created_at > (select * from time_frame)
),
activity as (
select created_at::date as activity_date, org_id as unique_id, cohort_date
from events
join population on population.unique_id = org_id
where created_at > (select * from time_frame)
),
population_agg as (
select cohort_date, count(distinct unique_id) as total
from population
group by 1
)
select activity.cohort_date as date,
date_part('day',activity_date - activity.cohort_date) as day,
count(distinct unique_id) as value,
total
from activity
join population_agg on activity.cohort_date = population_agg.cohort_date
group by 1 , 2, 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment