gpt4 book ai didi

sql - 滚动每日不同计数

转载 作者:行者123 更新时间:2023-12-02 05:00:12 26 4
gpt4 key购买 nike

我们有一个包含以下列的表格:

SESSION_ID      USER_ID          CONNECT_TS
-------------- --------------- ---------------
1 99 2013-01-01 2:23:33
2 101 2013-01-01 2:23:55
3 104 2013-01-01 2:24:41
4 101 2013-01-01 2:24:43
5 233 2013-01-01 2:25:01

我们需要获取每天的不同用户数“活跃用户”的数量,“活跃用户”定义为在过去 45 天内使用过该应用程序的用户。这是我们的想法,但我觉得必须有更好的方法:

select trunc(a.connect_ts)
, count(distinct a.user_id) daily_users
, count(distinct b.user_id) active_users
from sessions a
join sessions b
on (b.connect_ts between trunc(a.connect_ts) - 45 and trunc(a.connect_ts))
where a.connect_ts between '01-jan-13' and '12-jun-13'
and b.connect_ts between '01-nov-12' and '12-jun-13'
group by trunc(a.connect_ts);

我们查看了窗口函数,但它似乎不支持不同的计数。我们还考虑过先将聚合加载到临时表中,但是不同的计数再次将其排除在外。有没有更好的方法来做到这一点?

最佳答案

要做的第一件事是生成您感兴趣的日子的列表:

select (trunc(sysdate, 'yyyy') -1) + level as ts_day
from dual
connect by level <= to_number( to_char(sysdate, 'DDD' ) )

这将生成一个从今年 1 月 1 日到今天的日期表。将您的表加入此子查询。使用交叉联接可能不是特别有效,具体取决于范围内的数据量。因此,请将此视为概念验证并根据需要进行调整。

with days as
( select (trunc(sysdate, 'yyyy') -1) + level as ts_day
from dual
connect by level <= to_number( to_char(sysdate, 'DDD' ) ) )
select days.ts_day
, sum ( case when trunc(connect_ts) = ts_day then 1 else 0 end ) as daily_users
, sum ( case when trunc(connect_ts) between ts_day - 45 and ts_day then 1 else 0 end ) as active_users
from days
cross join sessions
where connect_ts between trunc(sysdate, 'yyyy') - 45 and sysdate
group by ts_day
order by ts_day
/

关于sql - 滚动每日不同计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17099743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com