PostgreSQL

时间:2017-03-20 20:20:26

标签: sql postgresql group-by window-functions

每次将操作字段更改为值1时,我都需要为每个用户计数。如果第一个条目为1则计数也是如此。行无序,但应按action_date顺序计算。

换句话说,我认为需要做的是:按user_id对行进行分组,按时间戳排序,然后计算action = 1和action!=前一行的频率。

示例

create table t (
user_id int,
action_date timestamp,
action int
);

Insert into t(user_id, action_date, action)
values
(1, '2017-01-01 00:00:00', 1),
(2, '2017-01-01 00:00:00', 0),
(1, '2017-01-03 00:00:00', 1),
(2, '2017-01-03 00:00:00', 0),
(1, '2017-01-02 00:00:00', 1),
(2, '2017-01-02 00:00:00', 1),
(1, '2017-01-04 00:00:00', 1),
(2, '2017-01-04 00:00:00', 1);

结果应为

 user_id | count 
---------+-------
       1 |     1
       2 |     2

this回答的帮助下,我可以通过这种方式获得单个帐户的结果,

select user_id, count(*)
from (select user_id, action_date,action,lag(action) over(order by action_date) as prev_action
      from t where user_id=2
     ) t
where (action<>prev_action and action=1) or (action=1 and prev_action is null)
group by user_id;

但我很难尝试将其扩展到所有用户。

1 个答案:

答案 0 :(得分:2)

lag()功能与partition by

一起使用
select user_id, count(*)
from (select t.*,
             lag(action) over (partition by user_id order by action_date) as prev_action
      from t
     ) t
where (action = 1) and (prev_action is distinct from 1)
group by user_id;