Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - group by ID and a time interval from variable starting point

I've an event log table that records in each row ID and DT_EVENT, ie:

ID     DT_EVENT
-------------------------
1      14-MAR-11 00:00:01
2      14-MAR-11 00:02:00
3      14-MAR-11 00:05:01
1      14-MAR-11 00:08:01
3      14-MAR-11 00:22:00
1      14-MAR-11 15:00:01
1      14-MAR-11 15:15:01

I need to group by ID and + a time interval of, let's say, 20mins starting from the first event for ID. Something like:

EV_GROUP    ID      DT_FIRST_EVENT      DT_LAST_EVENT          N_EVENTS
-----------------------------------------------------------------------
1           1       14-MAR-11 00:00:01  14-MAR-11 00:08:01        2
2           2       14-MAR-11 00:02:00  14-MAR-11 00:02:00        1
3           3       14-MAR-11 00:05:01  14-MAR-11 00:22:00        2
4           1       14-MAR-11 15:00:01  14-MAR-11 15:15:01        2

I'm not sure on how to set up the group clause for that dt interval. Any idea on that?

like image 304
Gabriele B Avatar asked Nov 27 '25 09:11

Gabriele B


1 Answers

SELECT  id, diff, MIN(dt_event), MAX(dt_event)
FROM    (
        SELECT  t.*,
                TRUNC((dt_event - FIRST_VALUE(dt_event) OVER (PARTITION BY id ORDER BY dt_event)) * 86400 / 1200) AS diff
        FROM    mytable t
        )
GROUP BY
        id, diff
like image 192
Quassnoi Avatar answered Nov 28 '25 22:11

Quassnoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!