Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有办法在SQL中找到活动用户?_Sql_Postgresql - Fatal编程技术网

有没有办法在SQL中找到活动用户?

有没有办法在SQL中找到活动用户?,sql,postgresql,Sql,Postgresql,我正在尝试查找数据库中活动用户的总数。此处的活动用户定义为在所选日期或晚于所选日期注册事件的用户。因此,如果用户在第1天、第2天和第5天注册了一个事件,则在第1天、第2天、第3天、第4天和第5天,这些事件将被视为活动事件 我的原始数据集看起来像这样,这是一个示例-真正的数据集将运行长达365天,大约有1000个用户 Day ID 0 1 0 2 0 3 0 4 0 5 1 1 1 2 2 1 3 1

我正在尝试查找数据库中活动用户的总数。此处的活动用户定义为在所选日期或晚于所选日期注册事件的用户。因此,如果用户在第1天、第2天和第5天注册了一个事件,则在第1天、第2天、第3天、第4天和第5天,这些事件将被视为活动事件

我的原始数据集看起来像这样,这是一个示例-真正的数据集将运行长达365天,大约有1000个用户

Day    ID
0      1
0      2
0      3
0      4
0      5
1      1
1      2
2      1
3      1
4      1
4      2
如您所见,所有5个ID在第0天都处于活动状态,而2个ID 1和2在第4天之前都处于活动状态,因此我希望完成的表如下所示:

Day    Count
0      5
1      2
2      2
3      2
4      2
我已尝试使用以下查询:

select Day as days, sum(case when Day <= days then 1 else 0 end)
from df
但它给出了不正确的输出,只统计在每个特定日期活跃的用户


我不知道下一步该怎么办。有人有什么想法吗?非常感谢

有点冗长,但这应该可以:

with dt as (
        select 0 d, 1 id
        union all
        select 0 d, 2 id
        union all
        select 0 d, 3 id
        union all
        select 0 d, 4 id
        union all
        select 0 d, 5 id
        union all
        select 1 d, 1 id
        union all
        select 1 d, 2 id
        union all
        select 2 d, 1 id
        union all
        select 3 d, 1 id
        union all
        select 4 d, 1 id
        union all
        select 4 d, 2 id
)
, active_periods as (
        select id
                , min(d) min_d
                , max(d) max_d
        from dt
        group by id
)
, days as (
        select distinct d
        from dt
)
select d.d
        , count(ap.id)
from days d
join active_periods ap on d.d between ap.min_d and ap.max_d
group by 1
order by 1 asc
你需要按日计算

select
    id,
    count(*)
from df
GROUP BY
    id
我想我应该使用generate_系列:

如果您想从第1天算起所有人都是活跃的,但并非所有人在第1天都有值,那么请使用1而不是min_day


是一把小提琴。

谢谢@Georgi。这是可行的,但实际上给出的数据只是一个样本集。我实际上需要在长达365天的时间段内运行它,并随着时间的推移自动更新,因此不幸的是,这是不实际的:-抱歉,因为我可能应该在问题中提到这一点。按照您的逻辑,您必须每天更新所有365天,因此我在这里没有真正看到问题。谢谢!我不熟悉generate_系列或侧面;这似乎是一个很好的解决方案。有一件事:我得到错误消息无效操作:语法错误在或接近1。我看不到打字错误,你能帮我检查一下吗?@fpl。列定义中存在语法错误。我已经包括了一个DBFIDLE,以表明这是有效的。谢谢你,看起来很棒!哇,我以前也没用过小提琴。要学的东西很多:-
select gs.d, count(*)
from (select id, min(day) as min_day, max(day) as max_day
      from t
      group by id
     ) t cross join lateral
     generate_series(t.min_day, .max_day, 1) gs(d)
group by gs.d
order by gs.d;