2016-08-04 78 views
-1

我想計算我的行按ID分組,並按照與row_number() over(partition by id order by time)類似的時間值進行排序。但是我想在遇到特殊情況時重置行數。有條件地重置row_number

例如在下表中,當event = 'y'我想從1重新計數爲相同的ID。

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 

我嘗試了很多查詢,但沒有接近我的預期。

請問你能幫我嗎? 感謝您的幫助。

+1

這可能是重複的:http://stackoverflow.com/questions/3435538​​1/creating-a- rank-that-reset-on-a-specific-value-of-a-column – Nicarus

+0

確實如此,謝謝。我在研究期間沒有找到這個線索...... –

回答

2

您可以使用條件累計總和由event領域進一步劃分行:

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