2013-07-24 55 views
4

我已經設置了一個非常簡單的表格,代表2D環境中的點。 Id列是每一個點和的geom列的ID是點的二進制表示到該空間中:在postgresql中使用窗口函數的累計和的SQL查詢

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.. 

我試圖合併之和滯後功能,但是PostgreSQL的說,Windows函數不能嵌套。我對如何進行感到困惑。任何人都可以幫助我?

回答

2

既然你不能有超過另一個窗口功能(「不能嵌套」),你需要添加一個子查詢層窗函數(或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是獨一無二的 - 這是由您的主鍵保證。