簡體   English   中英

基於前一行結果的遞歸公式

[英]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

編寫一個實現以下簡單遞歸公式的選擇。
y_n+1 = y_n + x_n+1

考慮以下

select x, y0 + sum(x) over(order by i) as y
from cte, init           

如果應用於您問題中的樣本數據 - 輸出是

在此處輸入圖片說明

注意:您在問題中顯示的預期結果 - 與您提供的公式不匹配 - 所以顯然上面的輸出與您的問題中的不同:o)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM