Rolling Daily Distinct Counts

天涯浪子 提交于 2019-12-06 01:34:09

The first thing to do is generate a list of the days you're interesting in:

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

This will generate a table of dates from 01-JAN this year to today. Join your table to this sub-query. Using a cross join might not be particularly efficient, depending on how much data you have in the range. So please regard this as a proof of concept and tune as you need.

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
/

If Your version of Oracle supports WITH-statements, this might help You:

with sel as (
select trunc(a.connect_ts) as logon_day
, count(distinct user_id) as logon_count
from sessions
group by trunc(connect_ts)
)
select s1.logon_day
, s1.logon_count as daily_users
, (select sum(logon_count) from sel where logon_day between s1.logon_day - 45 and s1.logon_day) as active_users
from sel s1

otherwise You'll have to write it this way (which executes much slower...):

select sel.logon_day
, sel.logon_count as daily_users
, (select count(distinct user_id) as logon_count
      from t_ad_session
      where trunc(connect_ts) between sel.logon_day - 45 and sel.logon_day) as active_users
from (select trunc(connect_ts) as logon_day, count(distinct user_id) as logon_count
      from t_ad_session
      group by trunc(connect_ts)) sel
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!