我有张桌子看起来像,
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中实现。我可以将它封装在一个窗口函数中,但是自定义函数的实现似乎总是很复杂。
发布于 2014-11-05 22:02:25
您可以使用递归的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
;这是链接。
发布于 2014-11-05 21:58:50
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;https://stackoverflow.com/questions/26766477
复制相似问题