I have the next table that stores events: (simplified structure)
| ID | User | Action | Timestamp |
|---|---|---|---|
| 12 | user1 | END | 2022-01-01 05:00 |
| 43 | user1 | START | 2022-01-01 04:00 |
| 54 | user1 | END | 2022-01-01 03:00 |
| 13 | user1 | START | 2022-01-01 02:00 |
I need to join 2 events in one row, so any START event is accompanied by the END event that comes after that.
So the result should be the next:
| ID1 | ID2 | User | Start Timestamp | End Timestamp |
|---|---|---|---|---|
| 13 | 54 | user1 | 2022-01-01 02:00 | 2022-01-01 03:00 |
| 43 | 12 | user1 | 2022-01-01 04:00 | 2022-01-01 05:00 |
Ideally, it should not have to many performance issues, as there could be a lot of records in the table.
I've tried the next query:
select
s.id as "ID1",
e.id as "ID2",
s.user,
s.time as "Start Time",
e.time as "End Time"
from Events s
left join Events e on s.user = e.user
where s.action = 'START'
and e.action = 'END'
and s.timestamp < e.timestamp
but it will also match the record 13 to record 12. Is it possible to join the left side to right only once? (keeping in mind that is should be the next END record time-wise?
Thanks