I need a count for each user for every time the action field has been changed to the value 1. If the first entry is 1 that counts as well. The rows are out of order but should be counted in order by action_date.
In other words, what I believe needs to be done is: group the rows by user_id, order them by timestamp, and then count how often action=1 and action != the previous row.
Example
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);
The result should be
user_id | count
---------+-------
1 | 1
2 | 2
With help from this answer I can get the results for a single account this way,
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;
but am stuck trying to expand it to all users.