Hi I want to split data by x days' cohort.
SELECT
--earliest_time,
sum(case when by_day = 0 then 1 else 0 end) day_0,
sum(case when by_day > 0 and by_day <= 10 then 1 else 0 end) day_10,
sum(case when by_day > 10 and by_day <= 20 then 1 else 0 end) day_20,
sum(case when by_day > 20 and by_day <= 30 then 1 else 0 end) day_30,
sum(case when by_day > 30 and by_day <= 40 then 1 else 0 end) day_40,
sum(case when by_day > 40 and by_day <= 50 then 1 else 0 end) day_50,
sum(case when by_day > 50 and by_day <=60 then 1 else 0 end) day_60,
sum(case when by_day > 60 then 1 else 0 end) day_60plus
from cohort_days co
This splits the data into cohorts of 10 days. If I want to change it to 20 days' cohort, then I need to edit them 1 by 1. I want to just define x days' cohort once, then the data can generate the cohort groups itself automatically.
I want to know is there easier way to do this than the above code? For example, I just need to define x days' cohort once at the beginning then I can use loops to iterate over it to generate the rest of the cohort groups.
A bit like this:
declare @d int
select @d = 20
select * from cohort_days
SELECT
sum(case when by_day = 0 then 1 else 0 end) day_0,
sum(case when by_day > 0 and by_day <= @d then 1 else 0 end) CONCAT('ay_: ', @d),
select @2d = @d*2
sum(case when by_day > @d and by_day <= @2d then 1 else 0 end) CONCAT('ay_: ', @2d)
select @3d = @d*3
sum(case when by_day > @2d and by_day <= @3d then 1 else 0 end) CONCAT('ay_: ', @3d)
from cohort_days co
If I want to change cohort days to 50 days, I just need to change select @d = 20 to select @d = 50
