2016-08-04 54 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