如何解决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。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。