【问题标题】:how to find number of active users for say 1 day,2 days, 3 days.....postgreSQL如何查找 1 天、2 天、3 天的活跃用户数.....postgreSQL
【发布时间】:2019-04-22 17:36:59
【问题描述】:

一周内活跃 # 天的分布:我试图找出在 3 月 1 日至 3 月 7 日的特定周内 1 天、2 天、3 天、…7 天活跃的成员数量。

有什么方法可以在分区之上使用聚合函数吗? 如果不是,可以用什么来实现这一点?

select distinct memberID,count(date) over(partition by memberID) as no_of_days_active
from visitor
where date between '"2019-01-01 00:00:00"' and '"2019-01-07 00:00:00"'
order by no_of_days_active

结果应该是这样的

#Days Active    Count
1           20
2           32
3           678
4           34
5           3
6           678
7           2345

【问题讨论】:

    标签: sql postgresql windowing partition-by


    【解决方案1】:

    我认为您需要两个级别的聚合来计算一周中的天数:

    select num_days_active, count(*) as num_members
    from (select memberID, count(distinct date::date) as num_days_active
          from visitor
          where date >= '2019-01-01'::date and 
                date < '2019-01-08'::date
          group by memberID
         ) v
    group by num_days_active
    order by num_days_active;
    

    请注意,我更改了日期比较。如果您有时间组件,则 between 不起作用。而且,因为您在常量中包含了时间,所以我为count(distinct) 添加了到日期的显式转换。如果date 确实是一个没有时间成分的日期,那可能没有必要。

    【讨论】:

    • 谢谢戈丹。在子查询中添加了 group by 并正确获取结果。 select num_days_active, count(*) as num_members from (select memberID, count(distinct date::date) as num_days_active from visitor where date >= '2019-01-01'::date and date
    • @kk44 。 . .谢谢你。我确定了答案。
    【解决方案2】:

    借鉴@Gordon 的回答,我个人喜欢对子查询使用with 语句:

    with dat as (
        select distinct
            memberID,
            count(date) over(partition by memberID) as no_of_days_active
        from visitor
        where 1=1
            and date between '2019-01-01'::date and '2019-01-07'::date
        order by no_of_days_active
    )
    
    select 
        no_of_days_active, 
        count(no_of_days_active) no_of_days_active_cnt
    from dat
    group by no_of_days_active
    order by no_of_days_active
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-13
      • 2021-10-26
      相关资源
      最近更新 更多