我有这样的数据:
Date User ID
2012-10-11 a
2012-10-11 b
2012-10-12 c
2012-10-12 d
2012-10-13 e
2012-10-14 b
2012-10-14 e
我想做的是每天按最近两天的范围(在我的实际查询中是 7 天)分组,并获取不同用户 ID 的数量。
例如,我希望结果看起来像这样:
Date count(distinct userIDs)
2012-10-12 4
2012-10-13 3
2012-10-14 2
例如,对于 2012 年 10 月 12 日,我计数为 4,因为我有 'a'、'b'、'c',和'd'。 ' ==> 'a' 和 'b' 来自前一天,'c' 和 'd'从同一天开始,2012 年 10 月 12 日。
同样,对于 2012-10-13,我正在查看 2012-10-13 和 2012-10-12,我得到了'c','d' 和 'e'。
日期列的数据类型是日期。我正在使用 Teradata。
我一直在努力研究它,但找不到适用于我的情况的直接答案。 :-/对不起,如果这是重复的。非常感谢您的帮助。谢谢!
最佳答案
要执行您想要的操作,您实际上需要“乘以”数据,因为每一行都可以包含在最终聚合的两个日期中。
我认为最简单的方法是union all
方法:
select date, count(distinct userId)
from ((select date, UserId
from t
) union all
(select date + 1, UserId -- combine with yesterday's data
from t
)
) t
group by date;
因为您要处理 7 天,所以这里有另一种方法:
select (t.date + n), count(distinct t.UserId)
from t cross join
(select 0 as n union all select 1 union all select 2 union all select 3 union all
select 4 union all select 5 union all select 6
) n
group by t.date + n;
关于sql - 按日期范围分组 (teradata),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16725012/