计算列更改为postgres中特定值的位置

时间:2017-03-13 18:14:03

标签: 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:00:00 |      1
 2017-01-06 00:00:00 |      0
 2017-01-07 00:00:00 |      1

在此示例中,第1行,第5行和第7行计数,结果应为3.任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:2)

使用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