Oracle SQL 模拟嵌套窗口函数

问题描述

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

假设我们有一个包含四行数据的表 X,如下所示。

x
-
1
2
3
4

进一步,假设我们想从 X 派生出两列 a 和 b,使得

  • a = x + sum(b 的前几行按 x 排序)
  • b = a - 1。

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

因此,新表将具有如下所示的行。

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 是一个 dbfiddle。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...