PLPGSQL Function to Calculate Bearing

后端 未结 1 519
小鲜肉
小鲜肉 2021-01-24 04:02

Basically I can\'t get my head around the syntax of plpgsql and would appreciate some help with the following efforts. I have a table containing 1000\'s of wgs84 points. The fol

相关标签:
1条回答
  • 2021-01-24 05:04

    In PL/pgSQL it's most effective to do as much as is elegantly possible in basic SQL queries at once. You can largely simplify.

    I didn't get a definition of the sort order out of your question and left ??? to fill in for you:

    CREATE OR REPLACE FUNCTION get_bearings_from_points(_bgeom geometry)
      RETURNS TABLE (x numeric, y numeric, z numeric, bearing numeric) AS
    $func$
    BEGIN
       FOR x, y, z, bearing IN
          SELECT ST_X(t.wgs_geom), ST_Y(t.wgs_geom), ST_Z(t.wgs_geom)
               , ST_Azimuth(t.wgs_geom, lead(t.wgs_geom) OVER (ORDER BY ???))
          FROM   points_table t
          WHERE  ST_Within(t.local_geom, _bgeom)
          ORDER  BY ???
       LOOP
          RETURN NEXT;
       END LOOP;
    END
    $func$ LANGUAGE plpgsql;
    

    The window function lead() references a column from the next row according to sort order.

    This can be simplified further to a single SQL query - possibly wrapped into an SQL function:

    CREATE OR REPLACE FUNCTION get_bearings_from_points(_bgeom geometry)
      RETURNS TABLE (x numeric, y numeric, z numeric, bearing numeric) AS
    $func$
       SELECT ST_X(t.wgs_geom), ST_Y(t.wgs_geom), ST_Z(t.wgs_geom)
            , ST_Azimuth(t.wgs_geom, lead(t.wgs_geom) OVER (ORDER BY ???))
       FROM   points_table t
       WHERE  ST_Within(t.local_geom, $1)  -- use numbers in pg 9.1 or older
       ORDER  BY ???
    $func$ LANGUAGE sql;
    

    Parameter names can be referenced in pg 9.2 or later. Per release notes of pg 9.2:

    Allow SQL-language functions to reference parameters by name (Matthew Draper)

    0 讨论(0)
提交回复
热议问题