Este es un buen rompecabezas.
Como mi DBMS principal es Teradata, escribí una solución usando funciones analíticas (necesita TD14.10+):
SELECT dt.*,
-- find the last item in the stack with the same position
Last_Value(val IGNORE NULLS)
Over (PARTITION BY pos
ORDER BY i) AS top_of_stack_val
FROM
(
SELECT st.*,
-- calculate the number of items in the stack
Sum(CASE WHEN op = 'I' THEN 1 ELSE -1 end)
Over (ORDER BY i
ROWS Unbounded Preceding) AS pos
FROM stack_trace AS st
) AS dt;
Esta solución también funciona para Oracle, pero PostgreSQL y SQL Server no son compatibles con IGNORE NULLS
opción para LAST_VALUE
y emularlo es bastante complicado, por ejemplo, vea Itzk Ben-Gan's The Last non NULL Rompecabezas
Editar:De hecho, no es tan complejo, olvidé la segunda solución de Itzik, el viejo truco del piggyback;-)
El enfoque de Martin Smith funcionará para los cuatro DBMS.