我有一个包含登录事件信息的表。每次用户登录时,都会添加一条包含用户和日期的记录。我想在该表中计算一个新列,其中包含用户在过去31天内登录的次数(包括当前尝试次数)。这是我的表格的简化版本,包括我要添加的列:
UserID Date LoginsInPast31Days
-------- ------------- --------------------
1 01-01-2012 1
2 02-01-2012 1
2 10-01-2012 2
1 25-01-2012 2
2 03-02-2012 2
2 22-03-2012 1
我知道如何计算登录尝试的总次数:我使用COUNT(*) OVER (PARTITION BY UserId ORDER BY Date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
。但是,我想将时间范围限制为过去31天。我的猜测是我必须更改UNBOUNDED PRECEDING
,但如何更改它以便选择正确的行数?
答案 0 :(得分:1)
一种非常有效的方法是在每个日期后30天添加记录。它看起来像这样:
select userid, dte,
sum(inc) over (partition by userid order by dte) as LoginsInPast31Days
from ((select distinct userid, logindate as dte, 1 as inc from logins) union all
(select distinct userid, dateadd(day, 31, dte, -1 as inc from logins)
) l;
答案 1 :(得分:0)
你几乎在那里,2次调整:
结合这些提示,您将获得:
SELECT SUM(COUNT(*)) OVER (
PARTITION BY t.userid_KEY
ORDER BY CAST(t.login_ts AS DATE) DESC
ROWS BETWEEN CURRENT ROW AND 31 FOLLOWING
)
FROM table AS t
GROUP BY t.userid, CAST(t.login_ts AS DATE)