Acabo de probar el enfoque de Gordon usando PostgreSQL 9.5.4 y se quejó de que
lo que significa usar lag()
con FILTER
No se permite. Así que modifiqué la consulta de Gordon usando max()
, un marco de ventana diferente y CTE:
WITH subq AS (
SELECT
"user", event, time as event_b_time,
max(time) FILTER (WHERE event = 'A') OVER (
PARTITION BY "user"
ORDER BY time
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
) AS last_event_a_time
FROM events
ORDER BY time
)
SELECT
"user", event_b_time, last_event_a_time
FROM subq
WHERE event = 'B';
Verificado que esto funciona con PostgreSQL 9.5.4.
Gracias a Gordon por el FILTER
¡truco!