sql配置单元

7gyucuyw  于 2021-06-24  发布在  Hive
关注(0)|答案(1)|浏览(308)

我试图计算在28天的窗口时间内有多少不同的用户使用一个应用程序。例如,如果我站在2月28日,我想知道有多少不同的用户登录了这个应用程序。这里的诀窍是我只想数一次。因此,如果用户“22”记录了28次,我希望他们也算一次。
此外,用户在每个日期只能出现一次。

select b.date, count(DISTINCT a.id)
from table a,
 (SELECT distinct(date), date_sub(date,27) dt_start
  from table) b
where a.date >= b.dt_start and a.date <= b.fecha
group by b.date

但它不起作用
我想要的示例,带2天滑动窗口:

Input
Day  Id
1    A
1    B
2    C
2    A
3    B
3    D
4    D

Result:
Day   Count(distinct Id)
1     2
2     3
3     4
4     2

谢谢!:)

yeotifhr

yeotifhr1#

考虑一个相关的子查询:

select distinct t.date, 
       (select count(distinct sub.id)
        from mytable sub
        where sub.date >= date_sub(t.date, 27) 
          and sub.date <= t.date) as distinct_users_27_days
from mytable t

或者,按窗口时段对自联接进行聚合:

select t1.date, 
       count(distinct t2.id) as distinct_users_27_days
from mytable t1
cross join mytable t2 
where t2.date >= date_sub(t1.date, 27) 
  and t2.date <= t1.date
group by t1.date

相关问题