Skip to content
Advertisement

Distribute values across subsequent rows in Postgresql

I have two tables. One contains user state transitions.

And the other one contains user’s actions.

It is easy to union these tables and visually see in which state an action was performed.

Output:

How can I “fill the blanks” so the output will be like this?

Advertisement

Answer

This is a place where lag(ignore nulls) is really useful. But not available in Postgres. So you can do this in two steps. Assign groups based on state. Then spread the value:

Note that t is actually your union all query. I’ve abstracted it to a single table alias to illustrate the important part of the logic.

Also, you have ties in your data (rows with the same time). That means that the answer is indeterminate — ties can go either before or after the state with the same time.

Here is a db<>fiddle.

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