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

后端 未结 5 1241
醉梦人生
醉梦人生 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:08

    Personally I doubt that you will end up finding SQL that you can just use in all of SQL Server, Teradata, Postgres, and Oracle and that has acceptable performance if the table is at all large.

    A SQL Server solution (demo) would be as follows

    SELECT i,
           SUBSTRING(MAX(FORMAT(i, 'D10') + val) OVER (PARTITION BY Pos ORDER BY i 
                                                         ROWS UNBOUNDED PRECEDING), 11, 8000)
    FROM   (SELECT st.*,
                   sum(CASE WHEN op = 'I' THEN 1 ELSE -1 END) 
                      OVER (ORDER BY i ROWS UNBOUNDED PRECEDING) AS pos
            FROM   stack_trace st) t1
    ORDER  BY i; 
    

提交回复
热议问题