我有一个按TITLE
和TIME
排序的事件列表,例如:
TITLE |TIME
A |11:59
A |12:00
A |12:01
A |12:02
A |12:03
B |12:04
B |12:05
B |12:06
B |12:07
B |12:14
B |12:15
B |12:16
我想计算序列的START
和END
。序列是一组事件,其中分钟彼此之间没有相同TITLE
的间隙,例如:
TITLE |START |END
A |11:59 |12:03
B |12:04 |12:07
B |12:14 |12:16
答案 0 :(得分:2)
假设支持所有窗口功能,您可以使用lag
和运行总和来执行此操作,以根据1分钟的时差分配组。
select title,min(time) as start_time,max(time) as end_time
from (select title,time,sum(col) over(partition by title order by time) as grp
from (select title,time,
case when lag(time) over(partition by title order by time) - time = 1
/*change this calculation for 1 minute time difference*/
then 0 else 1 end as col
from tbl
) t
) t
group by title,grp
另一种方式是
select title,min(time),max(time)
from (
select title,time,
time-row_number() over(partition by title order by time) as grp
/*change this calculation to subtract row_number from time*/
from tbl
) t
group by title,grp