Querying DAU/MAU over time (daily)

前端 未结 4 1381
礼貌的吻别
礼貌的吻别 2021-02-04 07:08

I have a daily sessions table with columns user_id and date. I\'d like to graph out DAU/MAU (daily active users / monthly active users) on a daily basis. For example:

         


        
4条回答
  •  温柔的废话
    2021-02-04 07:53

    Assuming you have values for each day, you can get the total counts using a subquery and range between:

    with dau as (
          select date, count(userid) as dau
          from dailysessions ds
          group by date
         )
    select date, dau,
           sum(dau) over (order by date rows between -29 preceding and current row) as mau
    from dau;
    

    Unfortunately, I think you want distinct users rather than just user counts. That makes the problem much more difficult, especially because Postgres doesn't support count(distinct) as a window function.

    I think you have to do some sort of self join for this. Here is one method:

    with dau as (
          select date, count(distinct userid) as dau
          from dailysessions ds
          group by date
         )
    select date, dau,
           (select count(distinct user_id)
            from dailysessions ds
            where ds.date between date - 29 * interval '1 day' and date
           ) as mau
    from dau;
    

提交回复
热议问题