2017-04-13 91 views
1

我有一個網絡表,其中的節點由數組中的整數指定,我在輸入數據時已經進行了排序。整數對應於位置表中的ID,其包含空間中點的WKT表示。我如何計算從開始到結束的網絡距離?下面計算有序數組中節點之間的總距離

Network Table 
--------------- 
| Nodes   | 
--------------- 
| {1,2,3}  | 
--------------- 


Location Table 
--------------- 
| ID, Point  | 
--------------- 
| 1, (1,0)  | 
| 2, (2,0)  | 
| 3, (2,1)  | 
--------------- 

最簡單的情況中給出我想以產生用於上述簡單的情況的值2。結果應該擴展到複雜的網絡。

通過使用ST_distance我可以計算網絡中所有單個點之間的距離,但我努力保留數組描述的唯一路徑。

+0

什麼是距離?它是從第一個到最後一個點的數量還是距離? –

+0

從第一個到最後一個,通過中間節點的距離。 – fordy

回答

0

您需要<-> operator爲PostgreSQL的point型(你似乎有):

select network_id, sum(dist) 
from  (
    select  n.id network_id, point <-> lag(point) over (partition by n.id order by i) dist 
    from  network n 
    cross join unnest(nodes) i 
    join  location l on l.id = i 
) s 
group by network_id 

或者,如果你真的有幾何& PostGIS,你也可以使用ST_Distance(雖然<->supported by PostGIS too,因爲它是距離運營商的普遍 「形式」 反正):

select network_id, sum(dist) 
from  (
    select  n.id network_id, ST_Distance(point, lag(point) over (partition by n.id order by i)) dist 
    from  network n 
    cross join unnest(nodes) i 
    join  location l on l.id = i 
) s 
group by network_id 

http://rextester.com/ESQA1611

+0

他真正想要的是pg路由,因爲它是定向的。 –

1
with network (a) as (values ('{1,2,3}'::int[])) 
, location (id, p) as (values (1,'(1,0)'::point),(2,'(2,0)'),(3,'(2,1)')) 
select a, sum(dt) 
from (
    select 
     a, 
     abs(p[0] - lag(p[0]) over(partition by a order by id)) + 
     abs(p[1] - lag(p[1]) over(partition by a order by id)) as dt 
    from 
     (
      select a, unnest(a) as id 
      from network 
     ) network 
     inner join 
     location using (id) 
) s 
group by a 
; 
    a | sum 
---------+----- 
{1,2,3} | 2 

在PostGIS:

with network (a) as (values ('{1,2,3}'::int[])) 
, location (id, p) as (values 
    (1,st_makepoint(1,0)),(2,st_makepoint(2,0)),(3,st_makepoint(2,1)) 
) 
select a, sum(dt) 
from (
    select 
     a, 
     st_distance(p, lag(p) over(partition by a order by id)) as dt 
    from 
     (
      select a, unnest(a) as id 
      from network 
     ) network 
     inner join 
     location using (id) 
) s 
group by a 
; 
    a | sum 
---------+----- 
{1,2,3} | 2