【问题标题】:Oracle SQL to Mimic Nested Window FunctionOracle SQL 模拟嵌套窗口函数
【发布时间】:2021-02-10 00:58:59
【问题描述】:

我的实际问题涉及更大的行源和更多涉及的数学,但这是一个仍然展示所面临挑战的小例子。使用 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
;

也许分层查询可能会有所帮助,但不确定它是通过什么来连接的。

任何想法将不胜感激。提前致谢。

【问题讨论】:

    标签: sql oracle nested analytic-functions recursive-cte


    【解决方案1】:

    您可以使用递归 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。

    【讨论】:

      猜你喜欢
      • 2013-05-01
      • 2015-08-18
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 2021-10-18
      • 1970-01-01
      相关资源
      最近更新 更多