2016-08-04 17 views
-1

IDでグループ化された行をrow_number() over(partition by id order by time)のような時間の値で数えたいとします。しかし、私は特別な条件に遭遇したときに行数をリセットしたい。条件付きでrow_numberをリセットする

たとえば、下の表のevent = 'y'と同じIDの場合は1から再計算します。

id   time      event  rank 
----------- ------------------------- ---------- ---------- 
400   2016-07-09 11:31:30  y   1 
400   2016-07-09 11:31:31  x   2 
400   2016-07-09 11:31:37  x   3 
400   2016-07-09 11:31:38  x   4 
400   2016-07-09 11:31:42  y   1 
400   2016-07-09 11:31:43  x   2 
400   2016-07-09 11:31:44  x   3 
400   2016-07-09 11:31:59  y   1 
400   2016-07-09 11:32:43  x   2 
400   2016-07-09 11:33:44  x   3 
401   2016-07-09 10:31:30  y   1 
401   2016-07-09 10:31:31  x   2 
401   2016-07-09 10:37:37  x   3 
401   2016-07-09 10:38:38  x   4 
401   2016-07-09 11:05:42  y   1 
401   2016-07-09 11:07:43  x   2 
401   2016-07-09 11:31:44  x   3 

私は多くのクエリを試しましたが、私が期待するものに近いものはありません。

お願いします。 ありがとうございました。

あなたはさらに eventフィールドで行を分割するために、条件付き累積和を使用することができます
+1

これは、の重複ことがありますhttp://stackoverflow.com/questions/3435538​​1/creating-a-特定の値でリセットされるランク – Nicarus

+0

本当にありがとうございます。私の研究中にこのスレッドは見つかりませんでした... –

答えて

2

with cte as (
    select id, time, event, 
     sum(case when event = 'y' then 1 else 0 end) over (partition by id order by time) as group_id 
    from tbl 
) 
select id, time, event, 
     row_number() over (partition by id, group_id order by time) as rank 
    from cte