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

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

    Although it does require an additional step -

    Generic solution for Hive, Teradata, Oracle, SQL Server and PostgreSQL

    select      s.i
    
               ,min (s.val) over
                (
                    partition by    s.depth
                                   ,s.depth_val_seq
                )                                   as top_of_stack_val            
    
    from       (select      s.i
                           ,s.val
                           ,s.depth
                            
                           ,count (s.val) over 
                            (
                                partition by    s.depth
                                order by        s.i
                                rows            between unbounded preceding and current row
                            )                                                                   as depth_val_seq
                             
                from       (select      s.i
                                       ,s.val
                                        
                                       ,sum (case s.op when 'I' then 1 else -1 end)   over
                                        (
                                            order by        s.i
                                            rows            between unbounded preceding and current row
                                        )                                                                   as depth
                 
                            from        stack_trace s
                            )
                            s
                )
                s
     
    order by    i
    ;
    

提交回复
热议问题