Skip to content

Instantly share code, notes, and snippets.

@fadur
Created October 6, 2015 00:02
Show Gist options
  • Save fadur/e3f80f4283699c410747 to your computer and use it in GitHub Desktop.
Save fadur/e3f80f4283699c410747 to your computer and use it in GitHub Desktop.
select date_trunc('month', start_date), sum(count(user_id))
over (
PARTITION by date_trunc('month', start_date)
ROWS BETWEEN 24 PRECEDING AND 1 PRECEDING
)
from cart_orders
where status in (1,2)
group by 1
order by 1;
@smirnoffs
Copy link

Even better

select date_trunc('month', start_date), sum(count(user_id))
 over (
    PARTITION by date_trunc('month', start_date)
    ROWS BETWEEN 24 PRECEDING AND CURRENT ROW
)
from cart_orders
where status in (1,2)
group by 1
order by 1;

@flux0r
Copy link

flux0r commented Oct 6, 2015

I was thinking something like the following.

select
        mth
        , cohort_size new_users_this_month
        -- We want to order by the month and then sum the current row and the 23 before it (for a total of 24)
        , sum(cohort_size) over (order by mth rows between 23 preceding and current row) new_users_in_window
from
        (
                -- We want the start month and the number of people who started in that start month.
                select
                        date_trunc('month', start_date) mth
                        , count(distinct user_id) cohort_size
                from
                        cart_orders
                where
                        status in (1, 2)
                group by
                        date_trunc('month', start_date)
        ) a
order by
        mth desc

You can check the results by copying into a spreadsheet and selecting 24 month windows for the new_users_this_month field.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment