Oracle SQL 模仿嵌套 Window 函数

Oracle SQL to Mimic Nested Window Function

我的实际问题涉及更大的行源和更多的数学,但这是一个小例子,仍然展示了所面临的挑战。使用 Oracle 19c.

假设我们有一个 table X 有如下四行数据。

x
-
1
2
3
4

此外,假设我们要从 X 中导出两列 a 和 b,使得

如果没有前面的行,则总和为 0。

因此,新的 table 将包含如下行。

x a b
- - -
1 1 0
2 2 1
3 4 3
4 8 7

以下内容无效 SQL,但提供了正在尝试的示例。

with
  X AS
  (
    select 1 x from dual
    union all select 2 from dual
    union all select 3 from dual
    union all select 4 from dual
  )
  , A AS
  (
    select
      x
      , x + sum(b) over (order by x range between unbounded preceding and 1 preceding) AS a
      , a - 1 AS b
    from x
  )
  select * from A
;

也许分层查询可能有帮助,但不确定连接的依据是什么。

如有任何想法,我们将不胜感激。提前致谢。

您可以使用递归 CTE 执行此操作:

with X AS (
    select 1 x from dual
    union all select 2 from dual
    union all select 3 from dual
    union all select 4 from dual
  ),
     cte(x, a, b, b_sum) as (
      select x, x as a, x - 1 as b, x - 1 as b_sum
      from x
      where x = 1
      union all
      select x.x, x.x + cte.b_sum, x.x + cte.b_sum - 1, cte.b_sum + (x.x + cte.b_sum - 1)
      from cte join
           x
           on x.x = cte.x + 1
     )
select *
from cte;

Here 是一个 db<>fiddle.