我有一张表,
x y
1 2
2 null
3 null
1 null
11 null
我想通过滚动来填充空值 使用sql尽可能简单地应用y_ {i + 1} = y_ {i} + x_ {i + 1}的函数(inplace)
所以预期的结果
x y
1 2
2 4
3 7
1 8
11 19
在postgresql中实现。我可以将它封装在一个窗口函数中,但自定义函数的实现似乎总是很复杂
答案 0 :(得分:1)
WITH RECURSIVE t AS (
select x, y, 1 as rank from my_table where y is not null
UNION ALL
SELECT A.x, A.x+ t.y y , t.rank + 1 rank FROM t
inner join
(select row_number() over () rank, x, y from my_table ) A
on t.rank+1 = A.rank
)
SELECT x,y FROM t;
答案 1 :(得分:0)
您可以使用递归CTE迭代行。但是为了做到这一点,你需要一种从一行跳到另一行的方法。以下是使用ID列的示例:
; with recursive cte as
(
select id
, y
from Table1
where id = 1
union all
select cur.id
, prev.y + cur.x
from Table1 cur
join cte prev
on cur.id = prev.id + 1
)
select *
from cte
;
您可以在SQL Fiddle查看该查询。如果您没有ID列,但您确实有其他方式订购行,则可以使用row_number()
获取ID:
; with recursive sorted as
(
-- Specify your ordering here. This example sorts by the dt column.
select row_number() over (order by dt) as id
, *
from Table1
)
, cte as
(
select id
, y
from sorted
where id = 1
union all
select cur.id
, prev.y + cur.x
from sorted cur
join cte prev
on cur.id = prev.id + 1
)
select *
from cte
;