Postgres:计算时间间隔内的用户操作数

时间:2018-12-27 13:31:57

标签: postgresql

我正在尝试通过指定的动作来计算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

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以进行横向联接,以计算该用户在过去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.

答案 1 :(得分:1)

在Postgres上使用累计金额:

select
    dt, user_id, amount_actions,
    to_char(dt, 'WWYYYY') wk,
    sum(amount_actions) 
        over 
        (partition by user_id, to_char(dt, 'WWYYYY')
         order by user_id, dt) rolling_sum_7_days
from
    tbl
order by user_id, dt;

分区为:user_id + WeekYear to_char(dt,'WWYYYY')

dt         | user_id | amount_actions | wk     | rolling_sum_7_days
:--------- | ------: | -------------: | :----- | -----------------:
2018-12-01 |       1 |              2 | 482018 |                  2
2018-12-02 |       1 |              1 | 482018 |                  3
2018-12-10 |       1 |              1 | 502018 |                  1
2018-12-01 |       2 |              2 | 482018 |                  2
2018-12-02 |       2 |              1 | 482018 |                  3
2018-12-10 |       3 |              1 | 502018 |                  1

db <>提琴this