如何在表的列上进行航位推算,postgresql
我有一张桌子看起来像如何在表的列上进行航位推算,postgresql,postgresql,Postgresql,我有一张桌子看起来像 x y 1 2 2 null 3 null 1 null 11 null 我想通过执行滚动来填充空值 函数使用sql尽可能简单地应用y{i+1}=y{i}+x{i+1}(就地) 那么预期的结果呢 x y 1 2 2 4 3 7 1 8 11 19 在postgresql中实现。我可以将其封装在窗口函数中,但自定义函数的实现似乎总是很复杂您可以使用递归CTE迭代行。但为了做到这一点,您需要一种从一行跳到另
x y
1 2
2 null
3 null
1 null
11 null
我想通过执行滚动来填充空值
函数使用sql尽可能简单地应用y{i+1}=y{i}+x{i+1}(就地)
那么预期的结果呢
x y
1 2
2 4
3 7
1 8
11 19
在postgresql中实现。我可以将其封装在窗口函数中,但自定义函数的实现似乎总是很复杂您可以使用递归CTE迭代行。但为了做到这一点,您需要一种从一行跳到另一行的方法。下面是一个使用ID列的示例:
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;
; 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
;
您可以在中查看查询。如果没有ID列,但有另一种方式对行进行排序,则可以使用row\u 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
;
这是我尝试过的带有滞后聚合函数的窗口函数,但它只允许一次计算,不能沿列HMM传播计算。闻起来像是递归的……表是无序的集合。是否存在
id
列,或者如何确定行的顺序?`+1这似乎是正确的,但是over()
如何确定行的顺序?例如,它是否可以将带有y的行标记为非空
作为数字2,将其加倍并省略另一行?