【问题标题】:How to count distinct users on a 28-day sliding window - SQL Hive如何在 28 天的滑动窗口中统计不同的用户 - SQL Hive
【发布时间】:2019-10-03 00:07:12
【问题描述】:

我正在尝试计算在 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

谢谢! :)

【问题讨论】:

  • 您使用的是什么数据库? Hadoop 是一个并行框架。这一点非常重要,因为日期函数因数据库而异。
  • 哦,对不起,我正在使用 Hive。我也改了标题。谢谢:D
  • 你使用的两张表是什么。您只显示一个表作为输入,并且列与查询中的内容不匹配。
  • 哈哈,我很笨。只有一张表有 2 列,日期和 ID。我现在编辑了它。

标签: sql hive count sliding-window


【解决方案1】:

考虑一个相关的子查询:

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

【讨论】:

  • 在第一个答案解决方案中,我得到:“ParseException line 2:8 cannot identify input near '(' 'select' 'count' in expression specification”在第二个答案中:“第 5:6 行在 JOIN '27' 中遇到左右别名”此外,您不能在 Hive 的连接条件上使用 > 或
  • 查看编辑。我错过了 id 上的别名。如果cross join 不起作用,请用逗号替换。可能 hive 不支持count(distinct...)
猜你喜欢
  • 2015-02-17
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 2018-06-23
  • 2012-03-04
  • 2013-10-27
相关资源
最近更新 更多