使用postgresql中的窗口函数对累积和的SQL查询

我已经设置了一个非常简单的表,表示2D环境中的点. 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是唯一的 – 这由主键保证.

点赞