我试图通过指定的操作来计算 DAU 的种类,其中用户在某个时间间隔内按照他们的操作数量进行分类。

原始数据示例:

date        user_id   amount_actions
2018-12-01  1         2
2018-12-02  1         1
2018-12-10  1         1
2018-12-01  2         2
2018-12-02  2         1
2018-12-10  3         1

结果表我希望我能有:
date        user_id   amount_actions rolling_sum_7_days
2018-12-01  1         2              2
2018-12-02  1         1              3
2018-12-10  1         1              1
2018-12-01  2         2              2
2018-12-12  2         1              1
2018-12-10  3         1              1
2018-12-15  3         1              2

谢谢。

最佳答案

您可以执行横向连接,计算过去 7 天内该用户的操作总和:

select  date
,       user_id
,       amount_actions
,       sum_actions
from    YourTable yt1
cross join lateral
        (
        select  sum(amount_actions) as sum_actions
        from    YourTable yt2
        where   yt1.user_id = yt2.user_id
                and yt1.date - interval '7 days' < yt2.date
                and yt2.date <= yt1.date
        ) sum_actions

Working example at rextester.

关于postgresql - Postgres : Count number of users actions within time interval,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53945936/

10-16 15:19