[英]Postgres query for recursive operation on rows
create table foo (a int, b float);
insert into foo values (1, 2), (2,3),(3,2.5),(4,1.5);
a | b
---+-----
1 | 2
2 | 3
3 | 2.5
4 | 1.5
I want to calculate the difference of each b
for any a
我想计算任何
a
的每个b
的差
select RECURSIVE diff (?,?) on b where a=1
OUTPUT: OUTPUT:
a | diff
---+-----
1 | 0
2 | 1
3 | .5
4 | -.5
Is it possible to recursively apply a function over all of the table rows? 是否可以在所有表行上递归应用函数?
You can use the LAG
window function to get the diff between to rows: 您可以使用
LAG
窗口函数获取行之间的差异:
SELECT b - LAG(b) OVER (ORDER BY a ASC)
FROM foo;
┌──────────┐
│ ?column? │
├──────────┤
│ (null) │
│ 1 │
│ -0.5 │
│ -1 │
└──────────┘
(4 rows)
You can then SUM
that: 然后,您可以
SUM
:
SELECT SUM(d) OVER (ORDER BY a ASC)
FROM (
SELECT a, b - LAG(b) OVER (ORDER BY a ASC)
FROM foo
) sub(a, d);
┌────────┐
│ sum │
├────────┤
│ (null) │
│ 1 │
│ 0.5 │
│ -0.5 │
└────────┘
(4 rows)
select b - b0
from
foo
cross join
(select b as b0 from foo where a = 1) s
;
?column?
----------
0
1
0.5
-0.5
Due to the thousands of requests in the comments this is the elegant version: 由于注释中有成千上万的请求,因此这是一个优雅的版本:
select f1.b - f2.b
from
foo f1
cross join
foo f2
where f2.a = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.