SQL 挑战/谜题:给定堆栈跟踪 - 如何在每个时间点找到顶部元素? [英] SQL Challenge/Puzzle: Given a stack trace - How to find the top element at each point in time?

查看:30
本文介绍了SQL 挑战/谜题:给定堆栈跟踪 - 如何在每个时间点找到顶部元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 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 operations. I understood that solving this problem will also solve the original problem.
  • op 列实际上可以从问题中删除.当 val 为 NULL 时,它是一个 POP 操作,否则它是一个 PUSH 操作.
  • The op column can actually be removed from the question. When val is NULL then it is a POP operation otherwise it is a PUSH operation.

一个表,stack_trace,包含以下列:

A table, stack_trace ,contains the following columns:

  • i - 表示时间点的整数值.
  • op - 2 种可能的操作:I(in"/push")和 O(out"/pop").
  • val - 由in"/push"操作插入的值,或者out"/pop"操作插入的值.

  • i - Integer value that represents a point in time.
  • op - 2 possible operations: I ("in"/"push") and O ("out"/"pop").
  • val - The value inserted by the "in"/"push" operation or NULL for "out"/"pop" operation.

目标是找出堆栈顶部的值,在每个时间点 (i).

The goal is to find what was the value at the top of the stack, at each point in time (i).

例如

(NULL 值在此处表示为空格)

(NULL values are represented here as empty spaces)

数据:

i   op  val 
--  --  --  
1   I   A   
2   I   B   
3   O
4   I   C
5   O    
6   O   

要求的结果:

i   top_of_stack_val
--  ----------------
1   A
2   B
3   A
4   C
5   A
6   

要求

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆