[英]Recursive Formula based on previous Row's Result
讓我們考慮以下查詢:
with
init as (
select 0.1 as y0
),
cte as (
select 1 as i, 1 as x -- x_1
union all
select 2 as i, 10 as x -- x_2
union all
select 3 as i, 100 as x -- x_3
order by i asc
)
select cte.x, init.y0 -- <- ?
from cte
join init
on true
有一個 CTE init
指定初始值 y_0 和一個 CTE cte
指定具有值x
和索引i
。
我的問題是我是否可以寫一個select
它實現了以下簡單,遞推公式。
y_n+1 = y_n + x_n+1
因此,結果應該是 3 行,其值分別為: 1.1, 3.1, 6.1
(對於y_1, y_2, y_3
)。
那可能嗎?
您需要使用“OVER”語句。 您可以查看有關語法的更多文檔。
with
init as (
select 0.1 as y0
),
cte as (
select 1 as ts, 1 as i, 1 as x -- x_1
union all
select 2, 2, 10 as x -- x_2
union all
select 3, 3, 100 as x
union all
select 4, 4, 109 as x -- x_3
union all
select 5, 5, 149 as x
order by i asc
)
SELECT *,init.y0 + SUM(i) OVER(
ORDER BY (ts)
) AS res
FROM cte join init
on true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.