If your events are series of events in time - try to play with the MATCH()
clause and its dependent functions event_name()
, pattern_id()
and match_id()
.
I just created a timeseries out of your input letters, spaced by one-hour intervals, and applied a MATCH()
clause. If the PATTERN pat AS ()
clause uncannily reminds you of a grep
expression, that's the way it works.
Just look at the query's output - and imagine how many interesting things you could do with the pattern_id
-s and the match_id
-s that you get- grouping by them, for example, in subsequent SELECT-s ...
WITH
s(tm,event) AS (
SELECT TIME '00:00:00','A'
UNION ALL SELECT TIME '01:00:00','B'
UNION ALL SELECT TIME '02:00:00','C'
UNION ALL SELECT TIME '03:00:00','D'
UNION ALL SELECT TIME '04:00:00','E'
UNION ALL SELECT TIME '05:00:00','F'
UNION ALL SELECT TIME '06:00:00','G'
UNION ALL SELECT TIME '07:00:00','H'
UNION ALL SELECT TIME '08:00:00','B'
UNION ALL SELECT TIME '09:00:00','C'
UNION ALL SELECT TIME '10:00:00','D'
UNION ALL SELECT TIME '11:00:00','H'
UNION ALL SELECT TIME '12:00:00','C'
UNION ALL SELECT TIME '13:00:00','D'
UNION ALL SELECT TIME '14:00:00','E'
UNION ALL SELECT TIME '15:00:00','F'
UNION ALL SELECT TIME '16:00:00','H'
UNION ALL SELECT TIME '17:00:00','E'
UNION ALL SELECT TIME '18:00:00','F'
UNION ALL SELECT TIME '19:00:00','G'
UNION ALL SELECT TIME '20:00:00','H'
)
SELECT
*
, event_name()
, pattern_id()
, match_id()
FROM s
MATCH(
PARTITION BY 1 -- nothing to partition by
ORDER BY tm
DEFINE
START_ev AS (event='A')
, any_ev AS (event NOT IN ('A','H'))
, END_ev AS (event='H')
PATTERN pat AS (start_ev* any_ev+ end_ev)
ROWS MATCH FIRST EVENT
);
tm |event|event_name|pattern_id|match_id
00:00:00|A |START_ev | 1| 1
01:00:00|B |any_ev | 1| 2
02:00:00|C |any_ev | 1| 3
03:00:00|D |any_ev | 1| 4
04:00:00|E |any_ev | 1| 5
05:00:00|F |any_ev | 1| 6
06:00:00|G |any_ev | 1| 7
07:00:00|H |END_ev | 1| 8
08:00:00|B |any_ev | 2| 1
09:00:00|C |any_ev | 2| 2
10:00:00|D |any_ev | 2| 3
11:00:00|H |END_ev | 2| 4
12:00:00|C |any_ev | 3| 1
13:00:00|D |any_ev | 3| 2
14:00:00|E |any_ev | 3| 3
15:00:00|F |any_ev | 3| 4
16:00:00|H |END_ev | 3| 5
17:00:00|E |any_ev | 4| 1
18:00:00|F |any_ev | 4| 2
19:00:00|G |any_ev | 4| 3
20:00:00|H |END_ev | 4| 4