Sql 在postgres中将列更改为特定值的位置计数

Sql 在postgres中将列更改为特定值的位置计数,sql,postgresql,Sql,Postgresql,我需要一个行计数,其中action=1,action与上面的行不同。如果action=1,则第一行应计数 action_date | action ---------------------+-------- 2017-01-01 00:00:00 | 1 2017-01-02 00:00:00 | 1 2017-01-03 00:00:00 | 0 2017-01-04 00:00:00 | 0 2017-01-05 00:

我需要一个行计数,其中action=1,action与上面的行不同。如果action=1,则第一行应计数

     action_date     | action 
---------------------+--------
 2017-01-01 00:00:00 |      1
 2017-01-02 00:00:00 |      1
 2017-01-03 00:00:00 |      0
 2017-01-04 00:00:00 |      0
 2017-01-05 00:00:00 |      1
 2017-01-06 00:00:00 |      0
 2017-01-07 00:00:00 |      1
在本例中,第1行、第5行和第7行计数,结果应为3。非常感谢您的帮助。

使用lag获取前一行的值,然后根据条件进行计数

select count(*)
from (select action_date,action,lag(action) over(order by action_date) as prev_action
      from t
     ) t
where (action<>prev_action and action=1) or (action=1 and prev_action is null)
或者可以简化为

select 
count(case when lag(action) over(order by action_date) is null then and action = 1 then 1
           when lag(action) over(order by action_date) is not null and lag(action) over(order by action_date) <> action and action = 1 then 1 
      end) as cnt
from t
使用lag获取上一行的值,然后根据条件进行计数

select count(*)
from (select action_date,action,lag(action) over(order by action_date) as prev_action
      from t
     ) t
where (action<>prev_action and action=1) or (action=1 and prev_action is null)
或者可以简化为

select 
count(case when lag(action) over(order by action_date) is null then and action = 1 then 1
           when lag(action) over(order by action_date) is not null and lag(action) over(order by action_date) <> action and action = 1 then 1 
      end) as cnt
from t

谢谢你的快速回复。答案不包括第一行的计数。如何将其包括在内?简化后的答案似乎并不正确,重点放在then和part上。修复此问题后,我得到一个异常,聚合函数调用不能包含窗口函数调用。感谢您的快速响应。答案不包括第一行的计数。如何将其包括在内?简化后的答案似乎并不正确,重点放在then和part上。修复此问题后,我得到一个异常,聚合函数调用不能包含窗口函数调用。