gpt4 book ai didi

在postgresql中使用窗口函数的SQL查询累计总和

转载 作者:行者123 更新时间:2023-11-29 11:29:28 25 4
gpt4 key购买 nike

我设置了一个非常简单的表格,代表二维环境中的点。 Id 列是每个点的 id,geom 列是点到空间的二进制表示:

public.foo

 Column |         Type         |                 Modifiers                  
--------+----------------------+--------------------------------------------
id | integer | not null default nextval('mseq'::regclass)
geom | geometry(Point,2100) |

索引:

    "foo_pkey" PRIMARY KEY, btree (id)
"foo_index_gist_geom" gist (geom)

要找到每个点到下一个点的距离,我正在使用这个窗口函数:

select 
id,
st_distance(geom,lag(geom,1) over (order by id asc)) distance
from
foo;

结果如下( st_distance(geom,geom) 给出两种 geom 数据类型之间的距离):

 id |     distance     
----+------------------
1 |
2 | 27746.1563439608
3 | 57361.8216245281
4 | 34563.3607734946
5 | 23421.2022073633
6 | 41367.8247514439
....

distance(1) -> null since its the first point
distance(2) -> ~28km from point 1 to point 2
distance(3) -> ~57km from point 2 to point 3
and etc..

我的目标是找到每个节点从每个点到下一个点的累积距离。例如下面这个模拟表:

 id |     distance     | acc 
----+------------------+-----
1 | |
2 | 27746.1563439608 | 27746.1563439608
3 | 57361.8216245281 | 85107.97797
4 | 34563.3607734946 | 119671.33874

where acc(1) is null because it is the first node,
acc(2) = acc(1) + dist(2)
acc(3) = acc(2) + dist(3)

and etc..

我尝试组合 sum 和 lag 函数,但 postgresql 说 Windows 函数不能嵌套。我对如何进行完全困惑。谁能帮助我?

最佳答案

因为你不能在另一个窗口函数之上有一个窗口函数(“不能嵌套”),你需要添加一个子查询层(或 CTE):

SELECT id, sum(distance) OVER (ORDER BY id) AS cum_dist
FROM (
SELECT id, st_distance(geom, lag(geom, 1) OVER (ORDER BY id)) AS distance
FROM foo
) sub
ORDER BY id;

这假设 id 是唯一的 - 这是由您的主键保证的。

关于在postgresql中使用窗口函数的SQL查询累计总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17837958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com