计算一列中不同条目之间的距离

时间:2018-10-29 15:05:12

标签: sql postgresql distance point

我的表格中有此类列:

Table A:

geom_etrs(geometry)
"0101000020E8640000FE2EAF0B3C981C414E499E34DFE65441"
"0101000020E864..."
"0101000020E875..."
"0101000020E867..."

如何计算每个条目之间的距离(它们已经定义为POINT)?

我想创建一个新列,其中显示1和2之间,2和3之间,然后3和4之间的距离,依此类推。

2 个答案:

答案 0 :(得分:1)

    select st_distance(point, lead(point,1) over (partition by rn)) 
 from ( select point, row_number() over (partition by id) as rn
 from table_1)t;


    gis=# \d users
     user_id | bigint    |  
     geog    | geography | 

select st_astext(geog), st_astext(lead(geog,1) over (partition by rn)) from ( select geog, row_number() over (partition by user_id) as rn from users limit 10)t;
                 st_astext                 |                 st_astext                 
-------------------------------------------+-------------------------------------------
 POINT(-70.0777937636872 41.6670617084209) | POINT(-70.0783833464664 41.6675384387944)
 POINT(-70.0783833464664 41.6675384387944) | POINT(-70.0793901822679 41.667476122803)
 POINT(-70.0793901822679 41.667476122803)  | POINT(-70.0787530494335 41.6671461707966)
 POINT(-70.0787530494335 41.6671461707966) | POINT(-70.07908017161 41.6663672501228)
 POINT(-70.07908017161 41.6663672501228)   | POINT(-70.0795407352778 41.6669886861798)
 POINT(-70.0795407352778 41.6669886861798) | POINT(-70.0798881265976 41.6663775240468)
 POINT(-70.0798881265976 41.6663775240468) | POINT(-70.0781470955597 41.6667824284963)
 POINT(-70.0781470955597 41.6667824284963) | POINT(-70.0790447962989 41.6675773546665)
 POINT(-70.0790447962989 41.6675773546665) | POINT(-70.0778760883834 41.6675017901701)
 POINT(-70.0778760883834 41.6675017901701) |

 gis=# select st_distance(geog, lead(geog,1) over (partition by rn)) from ( select geog, row_number() over (partition by user_id) as rn from users limit 10)t;
 st_distance  
--------------
  72.21147623
  84.13511302
  64.48606246
  90.70040367
  78.96272466
  73.78817244
 151.81026032
 115.69092832
  97.69189128

这应该对您有用

答案 1 :(得分:0)

使用window function LEAD会将下一个值作为当前值旁边的新列:demo:db<>fiddle(仅使用text类型,因为小提琴不支持{{ 1}},但相同)

geometry

现在您可以使用PostGIS的st_distance计算距离了:

SELECT 
    point_column,
    LEAD(point_column) OVER ()
FROM
    table
相关问题