2017-03-20 79 views
1

我需要爲每個用戶爲每一個動作欄已更改爲值1。如果第一項是1計數以及時間計數。該行是按順序,但應以通過ACTION_DATE計算。窗口函數的PostgreSQL

換句話說,我認爲需要做的事情是:GROUP BY USER_ID行,通過時間戳命令他們,再算上多久行動= 1和行動=前行!

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; 

但我堅持努力擴大到所有我們ERS。

回答

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; 
+0

我收到以下錯誤,當我嘗試這個'''錯誤:語法錯誤或接近 「(」 LINE 3:滯後(動作)以上(由USER_ID順序分區...''' – rurp

+0

非常感謝你對那優雅的答案,它完美的作品。 – rurp