2017-03-13 3 views
0

アクションの値が1で、アクションが上記の行と異なる行が必要です。 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になるはずです。

答えて

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

ように簡略化することができる迅速な対応をありがとうございました。答えには最初の行を数えません。どのようにそれを含めることができますか? – rurp

+0

編集された回答を参照してください。 –

+0

これは完全に機能します。どうもありがとうございました! – rurp

関連する問題