Oracle LEAD - return 下一个匹配列值

Oracle LEAD - return next matching column value

我有以下数据 table。

我想从 OUT 列中获取下一个输出数据。所以在下面的查询中使用了 LEAD 函数。

SELECT ROW_NUMBER,TIMESTAMP,IN,OUT,LEAD(OUT) OVER (PARTITION BY NULL ORDER BY TIMESTAMP) AS NEXT_OUT 
FROM MYTABLE;

它给出的数据如下 NEXT_OUT 列。

但我需要像 DESIRED 列一样按顺序知道匹配的下一列值。请告诉我如何在 Oracle LEAD FUNCTION

中实现此目的

谢谢

在 "in" 和 "out" 中枚举并使用该信息进行匹配。

select tin.*, tout.out as next_out
from (select t.*,
             count(in) over (order by timestamp) as seqnum_in
      from t
     ) tin left join
      (select t.*,
             count(out) over (order by timestamp) as seqnum_out
      from t
     ) tout
     on tin.in is not null and
        tout.out is not null and
        tin.seqnum_in = tout.seqnum_out;

分别为所有 IN 和 OUT 分配行号,通过将它们放在单个列中对结果进行排序并计算 LEAD:

WITH cte AS (
    SELECT t.*
         , CASE WHEN "IN"  IS NOT NULL THEN COUNT("IN")  OVER (ORDER BY "TIMESTAMP") END AS rn1
         , CASE WHEN "OUT" IS NOT NULL THEN COUNT("OUT") OVER (ORDER BY "TIMESTAMP") END AS rn2
    FROM t
)
SELECT cte.*
     , LEAD("OUT") OVER (ORDER BY COALESCE(rn1, rn2), rn1 NULLS LAST) AS NEXT_OUT
FROM cte
ORDER BY COALESCE(rn1, rn2), rn1 NULLS LAST

Demo on db<>fiddle