This demonstrates the use of the last_value()
window function over a entity-attribute-timestamp-value table in CockroachDB v22.2 to pivot it into a more conventional form. This works in PostgreSQL, too.
It is important to note that even though the last_value()
aggregate is operating on windows of data OVER (PARTITION BY entity, attribute ...)
the use of the ORDER BY updated_at
causes the default window frame to include data only up to the current row in the window. In order to create the desired lookahead behavior, the window frame must be expanded with ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
so that last_value()
can indeed see the last value in the window.