Skip to content
Advertisement

Postgres SQL attribution over time range

I’m using Postgres 11 and trying to figure out if I can do this in a single query.

Suppose I have two tables:

When I join these tables by uuid, Event2 rows should be attributed to a particular Event1.id up to when a newer Event1.id is active.

For example, if I have these rows:

Event1:

Event2:

I would get:

Event1.id == 10 would get attributed Event2 items from timestamp 01:00:00 until 02:10:59. Event1.id == 20 would get attributed Event2 items from timestamp 02:11:00 until 02:59:59. Event1.id == 20 would get attributed everything after 03:00:00.

Is this possible in SQL?

Advertisement

Answer

One approach is to use window functions to get the “next” event for each row in event1, and then it’s a simple join from there.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement