This is a nice puzzle.
As my main DBMS is Teradata I wrote a solution for it using Analytical functions (needs 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;
This solution works for Oracle, too, but PostgreSQL & SQL Server don't support the IGNORE NULLS
option for LAST_VALUE
and emulating it is quite complicated, e.g see Itzk Ben-Gan's The Last non NULL Puzzle
Edit: In fact it's not that complex, I forgot Itzik's 2nd solution, the old piggyback trick ;-)
Martin Smith's approach will work for all four DBMSes.