I am using Postgresql 13 and I have a table that looks something like this:
event_id | timestamp |
---|---|
1 | 2022-11-28 00:00:00 |
1 | 2022-11-28 00:00:10 |
2 | 2022-11-28 00:00:20 |
2 | 2022-11-28 00:00:30 |
2 | 2022-11-28 00:00:40 |
3 | 2022-11-28 00:00:50 |
3 | 2022-11-28 00:01:10 |
1 | 2022-11-28 00:01:20 |
2 | 2022-11-28 00:01:30 |
2 | 2022-11-28 00:01:40 |
3 | 2022-11-28 00:01:50 |
3 | 2022-11-28 00:02:10 |
3 | 2022-11-28 00:02:20 |
4 | 2022-11-28 00:02:30 |
I need to get monotonically increasing values for the event_id column based on the timestamp order. So the above table will become something like:
event_id | timestamp |
---|---|
1 | 2022-11-28 00:00:00 |
1 | 2022-11-28 00:00:10 |
2 | 2022-11-28 00:00:20 |
2 | 2022-11-28 00:00:30 |
2 | 2022-11-28 00:00:40 |
3 | 2022-11-28 00:00:50 |
3 | 2022-11-28 00:01:10 |
4 | 2022-11-28 00:01:20 |
5 | 2022-11-28 00:01:30 |
5 | 2022-11-28 00:01:40 |
6 | 2022-11-28 00:01:50 |
6 | 2022-11-28 00:02:10 |
6 | 2022-11-28 00:02:20 |
7 | 2022-11-28 00:02:30 |
Ideally I’d need this done in a single select statement, I tried a bunch of different approaches but nothing led me even close to what I need. Any suggestion? Thanks
2
Answers
You can assign a unique row number to each "chunk" of similar
event_id
s:See fiddle.
Try the following using a running sum of a flag that is set to 1 whenever event_id is changed over the increasing of timestamp.
See a demo.