SQL Challenge/Puzzle: Given a stack trace - How to find the top element at each point in time?

后端 未结 5 1213
醉梦人生
醉梦人生 2021-01-06 04:40
  • My real life use-case was to merge nested ranges. I\'ve drew some sketches and then I saw the resemblance between ranges starting and ending to stack PUSH and POP oper
5条回答
  •  一生所求
    2021-01-06 05:15

    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.

提交回复
热议问题