How to create a custom windowing function for PostgreSQL? (Running Average Example)

前端 未结 4 629
清歌不尽
清歌不尽 2021-01-05 00:34

I would really like to better understand what is involved in creating a UDF that operates over windows in PostgreSQL. I did some searching about how to create UDFs in genera

4条回答
  •  遥遥无期
    2021-01-05 01:03

    According to the documentation "Other window functions can be added by the user. Also, any built-in or user-defined normal aggregate function can be used as a window function." (section 4.2.8). That worked for me for computing stock split adjustments:

    CREATE OR REPLACE FUNCTION prod(float8, float8) RETURNS float8
      AS 'SELECT $1 * $2;'
      LANGUAGE SQL IMMUTABLE STRICT;
    
    CREATE AGGREGATE prods ( float8 ) (
      SFUNC = prod,
      STYPE = float8,
      INITCOND = 1.0
    );
    
    create or replace view demo.price_adjusted as
      select id, vd,
        prods(sdiv) OVER (PARTITION by id ORDER BY vd DESC ROWS UNBOUNDED PRECEDING) as adjf,
        rawprice * prods(sdiv) OVER (PARTITION by id ORDER BY vd DESC ROWS UNBOUNDED PRECEDING) as price
      from demo.prices_raw left outer join demo.adjustments using (id,vd);
    

    Here are the schemas of the two tables:

    CREATE TABLE demo.prices_raw (
      id VARCHAR(30),
      vd DATE,
      rawprice float8 );
    
    CREATE TABLE demo.adjustments (
      id VARCHAR(30),
      vd DATE,
      sdiv float);
    

提交回复
热议问题